.NET 4 代码契约:“需要未经验证:源!= null”
我刚刚开始在我的项目中使用代码契约。但是,我的存储库实现存在问题,它使用实体框架查询数据库。
我有以下方法:
public IEnumerable<Organization> GetAllOrganizations()
{
return _uow.CreateSet<Party>().OfType<Organization>().AsEnumerable();
}
该方法返回一个包含数据库中所有组织的集合,或者返回一个空集合,其中数据库中没有组织。
然而,根据 CodeContracts 的说法,这是不行的,它给了我错误:“requires unproven: source != null”
它想告诉我什么?我可以通过使用 Contract.Assume 来满足代码契约,假设它总是会找到一些东西,但随后我需要在从数据库读取数据的所有方法中执行此操作。
我是否在这里遗漏了一些东西,或者这是您使用数据库和 LINQ 时的预期行为?
I just started using code contracts in my project. However, I have a problem with my repository implementation, which queries my database using the Entity Framework.
I have the following method:
public IEnumerable<Organization> GetAllOrganizations()
{
return _uow.CreateSet<Party>().OfType<Organization>().AsEnumerable();
}
The method returns a collection containing all organizations in the database, or an empty collection there's not organizations in the database.
However, this is not okay according to CodeContracts, which give me the error: "requires unproven: source != null"
What is it trying to tell me? I can satisfy code contracts by using Contract.Assume, to assume that it would always find something, but then I need to do that in all methods that reads data from the database.
Am I missing something here, or is it intended behavior when you're working with databases and LINQ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是,CreateSet、OfType 和 AsEnumerable 方法之一被声明为带有名为“source”的 this 参数的扩展方法,而 CodeContrcts 无法证明它不为 null。另外,您不需要添加 Requires 子句来指定 _uow 在条目上不为空吗?
CreateSet 似乎是扩展方法,因为它没有出现在 MSDN 中。如果该方法不应该返回 null,您可以通过将此约定添加到
CreateSet
来强制执行此操作:当 CodeContracts 分析器看到此规则时,它将作为
OfType
输入的证据code> 不会为空,并且警告应该消失。My guess is that one of the methods CreateSet, OfType and AsEnumerable is declared as an extension method with a this-parameter called "source", and CodeContrcts can't prove it is not null. Also, don't you need to add a Requires clause to specify that _uow is non-null on entry?
CreateSet appears to be the extension method since it doesn't appear in MSDN. If the method should never return null, you can enforce this by adding this contract to
CreateSet
:When the CodeContracts analyzer sees this rule, it will take it as proof that the input to
OfType
will not be null, and the warning should go away.