问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/4951813/net-4-code-contracts-requires-unproven-source-null