[英]Entity Framework Code First - Abstract model class without primary key
我有定义主键的模型,但是现在我需要从我的抽象类中向该类添加继承。 问题在于,抽象类也需要主键。 PK属性的名称不同,并且必须不同。
例:
public abstract class AbstractModelClass
{
public int AbstractModelClassId { get; set; } // this key is required but I want him to not to be because I don't want to have 2 PK's
public string Prop1 { get; set; }
}
public class ModelClass : AbstractModelClass // before this class was not inherited but now I need this
{
public int ModelClassId { get; set; }
public int Prop2 { get; set; }
}
为什么主键不能在抽象类中,而在数据库中却是不同的表? 签出EF中Table per Concrete Type (TPC)
方法的Table per Concrete Type (TPC)
。 这里很好的解释:
样品:
public abstract class BillingDetail
{
[DatabaseGenerated(DatabaseGenerationOption.None)]
public int BillingDetailId { get; set; }
public string Owner { get; set; }
public string Number { get; set; }
}
public class BankAccount : BillingDetail
{
public string BankName { get; set; }
public string Swift { get; set; }
}
public class CreditCard : BillingDetail
{
public int CardType { get; set; }
public string ExpiryMonth { get; set; }
public string ExpiryYear { get; set; }
}
public class InheritanceMappingContext : DbContext
{
public DbSet<BillingDetail> BillingDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BankAccount>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("BankAccounts");
});
modelBuilder.Entity<CreditCard>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("CreditCards");
});
}
}
在这种情况下,我看不到AbstractModelClass中AbstractModelClassId的用途,因此一种解决方案将没有它。
但是由于某种原因,您需要该属性,但是不希望该属性进入Db表,则可以向其中添加[NotMapped]
属性。
[NotMapped]
public int AbstractModelClassId { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.