【问题标题】:Entity Framework, Code First 3 classes identical propertiesEntity Framework,Code First 3 类相同的属性
【发布时间】:2012-08-09 00:19:10
【问题描述】:

假设我有 3 种类型的 Html 类,它们具有相同的原语/导航属性:

  1. 公共虚拟字符串 HtmlTagName {get;设置;}
  2. 公共虚拟ICollection 属性{get;设置;}

    等等等等等等

这 3 个类之间的唯一区别是:

  1. 一个 Html 类可以有一组 Html 类(父 Html 类)
  2. 一个类可以是 Html 类的子类(子 Html 类)
  3. 一个类是独立的,即。它既不是另一个 html 类(单 Html 类)的父 html 类,也不是子 html 类

在我看来,有 3 类相同的属性,除了它是父母、孩子还是单身,因为没有(再次,因为大部分属性是相同的)。

【问题讨论】:

    标签: entity-framework-4


    【解决方案1】:

    我想我找到了答案,如果我错了,有人纠正我:

    public class HtmlElement : DelEntity
    {
        // Primitives
        public virtual string DisplayName { get; set; }
    
        // Foreign Key
        public virtual long? ParentElementId { get; set; } // If it is a child
    
        //Navigation - Class
        [ForeignKey("ParentElementId")]
        public virtual HtmlElement ParentHtmlElement { get; set; }        
    
        //Navigation - Collections (if it is a parent)
        private ICollection<HtmlElement> _childElements;
    
        [InverseProperty("ParentHtmlElement")]
        public virtual ICollection<HtmlElement> ChildElements
        {
            get { return _childElements ?? (_childElements = new HashSet<HtmlElement>()); }
            set { _childElements = value; }
        } 
    

    }

    【讨论】:

    • 是的,除非要求孩子永远不能变成父母等。然后你需要使用其他模式,例如继承。
    猜你喜欢
    • 2016-02-14
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多