3

考慮下面的代碼片段:代碼契約和流利的API與EF代碼第一個樣品

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); 
    } 
} 

在第8行(.HasOptional,.WithRequired)合約代碼分析工具,將產生以下兩個警告「CodeContracts:可能調用一個空引用的方法「

任何想法如何處理它?

回答

2

一種選擇是標記與[ContractVerification(假)]屬性整個方法:

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); 
    } 
} 

另外一個是添加數十Contract.Assume的()檢查:

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); 
    } 
} 

我們還有哪些其他選擇?你更傾向哪個?

1

我不知道EF,但我相信你不能只調整.Entity<User>()函數?此函數不指定它返回非空值的合約。試一下,如下:

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

P.S:我發現這個鏈接,你可能會感興趣,discussing Code Contracts and Entity Framework

+0

鏈接已死。 – 2016-07-11 10:29:17