3

Consider the following code snippet:

public partial class DatabaseContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Contract.Assume(modelBuilder != null);

        modelBuilder.Entity<User>()
            .HasOptional(x => x.Profile).WithRequired(x => x.User);

        base.OnModelCreating(modelBuilder);
    }
}

On line 8 (.HasOptional, .WithRequired) code contracts analysis tool produces the following two warnings "CodeContracts: Possibly calling a method on a null reference"

Any ideas how to deal with it?

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121

2 Answers2

2

One option is to mark the whole method with [ContractVerification(false)] attribute:

public partial class DatabaseContext : DbContext
{
    [ContractVerification(false)]
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasOptional(x => x.Profile).WithRequired(x => x.User);

        base.OnModelCreating(modelBuilder);
    }
}

Another one is to add dozens of Contract.Assume() checks:

public partial class DatabaseContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Contract.Assume(modelBuilder != null);

        var userEntity = modelBuilder.Entity<User>();
        Contracts.Assume(userEntity != null);
        var profileEntity = userEntity.HasOptional(x => x.Profile);
        Contracts.Assume(profileEntity != null);
        profileEntity.WithRequired(x => x.User);

        base.OnModelCreating(modelBuilder);
    }
}

Which other options do we have? Which one do you prefer?

Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121
1

I don't know EF, but I believe you can't just adjust the .Entity<User>() function? This function doesn't specify a contract that it returns a non null value. Try something as the following:

var userEntity = modelBuilder.Entity<User>();
Contract.Assert( userEntity != null );

P.s.: I found this link which might interest you, discussing Code Contracts and Entity Framework.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161