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?
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?