Entity Framework CodeFirst KeyNotFoundException in MemberDomainMap

天涯浪子 提交于 2019-12-01 00:26:45

Well, after much searching through my code and rebuilding from scratch I found that the problem was actually that I had a derived class of Node that had a Uri as a property, which obviously failed mapping since it doesn't have a default constructor (and possibly other reasons). I solved it for now by simply changing the property to a String which I validate as a Uri internally, though I would have preferred a more elegant solution. I tried mapping Uri and even a custom subclass (w/ default constructor) of Uri to a complextype, but that didn't help.

Still, the question above is answered.

With the @Paul's answer I could finally figure out my problem.

I am using EF with Inheritance TPT (Table per Type).

The source code

To make it easier I'll use the same classes discribed in this tutorial.

public abstract class BillingDetail
{
    public int BillingDetailId { get; set; }
    public string Owner { get; set; }
    public string Number { get; set; }
}

[Table("BankAccounts")]
public class BankAccount : BillingDetail
{
    public string BankName { get; set; }
    public string Swift { get; set; }
    public Agency Agency { get; set; } /* I added it */
}

public class InheritanceMappingContext : DbContext
{
    public DbSet<BillingDetail> BillingDetails { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<BankAccount>().ToTable("BankAccounts");
    modelBuilder.Entity<CreditCard>().ToTable("CreditCards");
}

The problem

Note that I've added a new property called Agency inside the BankAccount. Given it is a complex type, if you do not map it you'll get this annoying error at runtime!

Solution

What I did was simply ignore this property Agency, but you can also map it to EF know what to do. Both will stop the error.

The most weird thing is that even not mapping the derived entity (BankAccount) the problem occurs. It seems that EF somehow knows that you created the derivation. So, if you're trying to run EF without mapping some derivation you will probably get this error too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!