实体框架6 - 删除了继承抽象类的默认鉴别器列 - 错误3032:映射中的问题

时间:2017-07-01 21:01:56

标签: c# asp.net .net entity-framework entity-framework-6

错误:

error 3032: Problem in mapping fragments starting at line: Condition member '' with a condition other than 'IsNull=False' is mapped. Either remove the condition on or remove it from the mapping.

代码:

public enum MyEnum
{ 
    Value1, Value2
}

public class MyBaseClass
{ 
    public MyEnum MyEnum { get; protected set; }
}

public class DerivedOne: MyBaseClass
{
    public DerivedOne()
    {
        MyEnum = MyEnum.Value1;
    }

    public string MyDerivedOneString { get; set; }
}

public class DerivedTwo: MyBaseClass
{
    public DerivedTwo()
    {
        MyEnum = MyEnum.Value2;
    }
}

public class MyDbContext : DbContext
{
    DbSet<MyBaseClass> MyBaseClass { get; set; }

    DbSet<DerivedOne> DerivedOne { get; set; }

    DbSet<DerivedTwo> DerivedTwo { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<MyBaseClass>()
            .Map<DerivedOne>(x => x.Requires("MyEnum").HasValue((int)MyEnum.Value1))
            .Map<DerivedTwo>(x => x.Requires("MyEnum").HasValue((int)MyEnum.Value2));
    }
}

static void Main(string[] args)
{
    var db = new MyDbContext();

    var derivedOne = new DerivedOne();

    derivedOne.MyDerivedOneString = "test";

    db.DerivedOne.Add(derivedOne);
    //Exception
    db.SaveChanges();
}

1 个答案:

答案 0 :(得分:0)

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application

解决这个问题,它是一个每层次表(TPH)继承错误:

未编辑的类不会被编辑。

public abstract class MyBaseClass
{ 
    [NotMapped]
    public MyEnum MyEnum { get; protected set; }
}

public class MyDbContext : DbContext
{
    DbSet<MyBaseClass> MyBaseClass { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<MyBaseClass>()
            .Map<DerivedOne>(x => x.Requires("MyEnum").HasValue((int)MyEnum.Value1))
            .Map<DerivedTwo>(x => x.Requires("MyEnum").HasValue((int)MyEnum.Value2));
    }
}

static void Main(string[] args)
{
    var db = new MyDbContext();

    var derivedOne = new DerivedOne();

    derivedOne.MyDerivedOneString = "test";

    db.MyBaseClass.Add(derivedOne);

    db.SaveChanges();

    var test = db.MyBaseClass.OfType<DerivedOne>().FirstOrDefault();
}