代码合同和Fluent API与EF Code First Sample

时间:2011-04-19 11:12:27

标签: entity-framework ef-code-first code-contracts fluent-interface

请考虑以下代码段:

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:可能在空引用上调用方法”

任何想法如何处理它?<​​/ p>

2 个答案:

答案 0 :(得分:2)

一个选项是使用[ContractVerification(false)]属性标记整个方法:

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 :(得分:1)

我不知道EF,但我相信你不能只调整.Entity<User>()功能?此函数未指定返回非null值的约定。尝试以下内容:

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

P.s。:我找到了您可能感兴趣的链接,discussing Code Contracts and Entity Framework