繁体   English   中英

如何防止将父类的属性应用于子级的属性?

[英]How do I prevent an attribute on a property of a parent class from being applied to that property in the child?

我有一个父类ListableEntity ,该类的Description属性使用属性[DbUnique] ,该属性在SQL表中的此字段上放置了唯一约束。

public abstract partial class ParentEntity<T> {

    [DbUnique]
    public string Description { get; protected set; }
}

我需要创建一个ListableEntity的子类,该类不同于父类,允许其Description属性具有重复的值。 但是,即使我在子类中隐藏了parent属性,该DbUnique属性仍然以某种方式被应用,从而避免了重复的描述。 这是我为儿童班准备的相关摘录:

public class ChildEntity : ParentEntity<ChildEntity>
{
    public new string Description { get; private set; }
}

我是C#的新手。 我的理解是,此孩子的Description属性将覆盖父对象的ChildEntity对象,但是当尝试使用重复描述保存ChildEntities时,我仍然遇到异常,“无法插入具有唯一索引'IX_Description'的重复键行。” 有谁知道为什么仍要应用父属性中的此属性,以及如何防止这种情况发生? 谢谢。

您可以做两件事,一是更改属性名称,例如ParentDescription和ChildDescription(我认为这是最好的选择)。 另一个是再增加一个类,将属性“ Description”定为“抽象”,因此在子类中,您必须覆盖这些属性。

GrandParent-> ParentEntity-> ChildEntity

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM