开发者

EF Code-First inheritance & Primary Key problem

I'm trying to make a function that automatically adds an audit trail table when i need one. It kind of works but the only problem is that the audit table doesn't get the primary key i specified, it holds on to the earlier specified ItemId as the primary key.

It's because i am inheriting Department in ADepartment and already specified a primary key in the first EntityTypeConfiguration. I guess the EF is smart enough to realize that but it's not what i want.

Is there a way i can tell the second EntityTypeConfiguration that it should stop using ItemId as the primary key and start using AuditId for that?

    public class Item
    {
        public int ItemId { get; set;}
    }

    public class Department : Item
    {
        public string Name { get; set; }           
    }

    public class ADepartment : Department, IAudit
    {        
        public int AuditId { get; set; }        
    }


    EntityTypeConfiguration<Department> cfg = new EntityTypeConfiguration&l开发者_JS百科t;Department>();
    cfg.HasKey(p => p.ItemId);
    cfg.Map(p => p.MapInheritedProperties());                            
    cfg.ToTable(string.Format("Entity{0}", typeof(Department).Name));
    model.Configurations.Add<Department>(cfg);

    EntityTypeConfiguration<ADepartment> c = new EntityTypeConfiguration<ADepartment>();
    c.HasKey(p => p.AuditId);          
    c.Map(p => p.MapInheritedProperties());
    c.ToTable(string.Format("Audit{0}", typeof(ADepartment).Name));            
    model.Configurations.Add<ADepartment>(c);


No there is no way to do that. Entities in inheritance hierarchy must share a key properties. If you want different key for your audit record you need different entity type which is not inherited from the original type. Using inherited type for audit will cause you a lot of problems so you should do it anyway. For example:

  • Every your query will have to use OfType<Department> otherwise you will load audit records as well.
  • Lazy and eager loading of relations to Department will load both Department and ADepartment - there is no way to avoid this except using explicit loading with OfType<Department>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜