开发者

Entity framework with inheritance, condition, and foreign key

I just started to play around with Linq to entities and ran into an issue I can't figure out.

I am getting this error:

Condition member 'RelatedResources.TypeID' with a condition other than 'IsNull=False' is mapped. Either remove the condition on RelatedResources.TypeID or remove it from the mapping.

The condition that exists is a TypeID field in the abstract entity RelatedResource that defines the type of RelatedResource (Book, Link, guide, etc.). TypeID is also a foreign key and is mapped in th开发者_运维知识库e association with the Resource Type entity. I think this is the problem but I don't know how or why I should change this.


That usually happens when you have TypeID as a condition and also use it as a property. It might be causing problems because you are using it to map the association with ResourceType AND using it as a condition for the inheritance.


Is RelatedResources.TypeID set to be not null (ie. 'Isnull=false') in the database and in the entityframework schema?

Not sure you can both have that field as a conditional and acts as a foreign key to another table.

And would you need to if you using the conditional inheritance to determine the type?


Sounds like table-per-hierarchy (TPH) inheritance error:

https://learn.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

Use [NotMapped] on the base class property.

Pseudo code:

public abstract class MyBaseClass
{ 
    [NotMapped]
    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; }

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜