【发布时间】:2016-05-17 02:30:30
【问题描述】:
我有一个项目,我在构建代码优先数据模型时使用了继承。问题是我所有的实体类型都需要一个通用的“上下文 id”,表示为一个字符串:
public class EBaseGenericEntity
{
:
[Index("IX_Cid", IsUnique = true)]
public virtual string Cid { get; set; }
:
}
如您所见,“Cid”属性应始终保持唯一值。问题是:有一种实体类型的“Cid”值不必是唯一的,所以我认为这可行:
public class EEntityInfo : EBaseGenericEntity
{
:
[Index("IX_Cid", IsUnique = false)]
public override string Cid { get; set; }
:
}
唉,这让实体框架跌跌撞撞,抱怨:
类型“EEntityInfo”的属性“Cid”由两个名称为“IX_Cid”的 IndexAttributes 属性,其中包含冲突的配置: 索引属性属性 'IsUnique' = 'True' 与索引属性属性 'IsUnique' = 'False' 冲突。
在 EF/CF 中不能像这样覆盖属性的属性吗?
编辑:
为了确保问题不在于如何声明 IndexAttribute 以支持继承 (AttributeUsage.Inherited),我还尝试使用不同的 AttributeUsage 声明派生版本:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
public class IndexedAttribute : IndexAttribute
{
public IndexedAttribute(string name)
: base(name)
{
}
}
然后使用它代替“正常”的 IndexAttribute:
public class EBaseGenericEntity
{
:
[Indexed("IX_Cid", IsUnique = true)]
public virtual string Cid { get; set; }
:
}
public class EEntityInfo : EBaseGenericEntity
{
:
[Indexed("IX_Cid", IsUnique = false)]
public override string Cid { get; set; }
:
}
但这并没有帮助。我觉得奇怪的是 EF 可以找到 Indexed 自定义属性,尽管它(不可继承)使用。难道派生的自定义属性也不能覆盖它的AttributeUsage?
【问题讨论】:
标签: inheritance indexing ef-code-first