Entity Framework CodeFirst KeyNotFoundException in MemberDomainMap

前端 未结 3 1504
傲寒
傲寒 2021-01-06 16:55

Trying to run down an error in my EF datacontext implementation that is yielding a fairly cryptic error.

Test Name:  Nodes_can_be_saved
Test FullName:  MyP         


        
3条回答
  •  礼貌的吻别
    2021-01-06 17:36

    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 BillingDetails { get; set; }
    }
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity().ToTable("BankAccounts");
        modelBuilder.Entity().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.

提交回复
热议问题