我有这样的Master基类。
public class MasterTemplate
{
[Key]
public int Id { get; set; }
[StringLength(50)]
public string Code { get; set; }
[Required]
[StringLength(255)]
public string Description { get; set; }
public decimal? SortOrder { get; set; }
}
我有很多继承上述类的类。例如,种姓,国籍,货币等..,
public class Nationality : MasterTemplate
{
// Other memebers of nationality
}
public class Caste: MasterTemplate
{
// Other memebers of caste
}
大多数类都需要所有列,但我的一些类不需要“描述”,其中一些不需要“代码”,其他一些不需要“SortOrder”。
public class Zone: MasterTemplate
{
// Logic to mark Description [NotMapped],
// so that EF doesn't create a column in database
// Other memebers of zone
}
对于同一个类中的成员,我可以使用[NotMapped],但是如何从子类中为父类属性执行此操作。我知道我可以删除继承并执行它,但很想知道是否有可能从子类为父类属性执行此操作。
编辑:
正如@IvanJazz所建议的,修改代码如下。
public class MasterTemplate
{
[Key]
public int Id { get; set; }
[StringLength(50)]
public virtual string Code { get; set; }
[Required]
[StringLength(255)]
public virtual string Description { get; set; }
public virtual decimal? SortOrder { get; set; }
}
public class Nationality : MasterTemplate
{
// Code will not appear in Nationality table
[NotMapped]
public override string Code { get; set; }
}
public class Zone : MasterTemplate
{
// Description will not appear in Zone table
[NotMapped]
public override string Description { get; set; }
}
从逻辑上讲,实体框架在添加记录时不应搜索覆盖并标记为NotMapped属性。插入以下DbValidation时发生错误。不确定为什么实体框架仍在搜索未映射的属性。
你可以使用virtual
和override
修饰符来达到你想要的效果。使用virtual
属性将所有可选属性标记为override
和[NotMapped]
它们在派生类中。
public class MasterTemplate
{
[Key]
public int Id { get; set; }
[StringLength(50)]
public virtual string Code { get; set; }
[Required]
[StringLength(255)]
public virtual string Description { get; set; }
public virtual decimal? SortOrder { get; set; }
}
public class Nationality : MasterTemplate
{
// Code will not appear in Nationality table
[NotMapped]
public override string Code { get; set; }
}
public class Zone : MasterTemplate
{
// Description will not appear in Zone table
[NotMapped]
public override string Description { get; set; }
}