开发者

.NET 4 Code Contracts: "requires unproven: source != null"

开发者 https://www.devze.com 2023-02-09 08:47 出处:网络
I just started 开发者_如何学JAVAusing code contracts in my project. However, I have a problem with my repository implementation, which queries my database using the Entity Framework.

I just started 开发者_如何学JAVAusing 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?


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:

Contract.Ensures(Contract.Result<T>() != null);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号