Search code examples
c#.netnhibernateresharpercode-contracts

Code contracts together with frameworks not using it


I've got this code:

return session.Query<Payment>()
    .OrderBy(payment => payment.Created)
    .Skip((page - 1)*pageSize)
    .Take(pageSize)
    .ToArray();

Since NHibernate's Query method don't have any Contract.Ensures, I get this warning:

CodeContracts: requires unproven: source != null

To fix it, I write this:

var query = session.Query<Payment>();
Contract.Assume(query != null);
return query
    .OrderBy(payment => payment.Created)
    .Skip((page - 1)*pageSize)
    .Take(pageSize)
    .ToArray();

Is this the right way to do it? Now Resharper thinks query can be null since I compare it to null.

Possible 'null' assignment to entity marked with 'NotNull' attribute


Solution

  • Yes, that is the right way to do it. Resharper doesn't understand Code Contracts by default, check out this question to fix that.

    You might want to make a Query method inside your library which just calls NHibernate's Query but also has an Ensures contract, to save you having to use Assume everywhere.

    Something like (I'm guessing the types here):

    static IQueryable<T> MyQuery<T>(this Session s)
    {
        Contract.Requires(s != null);
        Contract.Ensures(Contract.Result<IQueryable<T>>() !=  null);
    
        var result = s.Query<T>();
        Contract.Assume(result != null);
        return result;
    }