简体   繁体   English

实体框架一对一表格

[英]Entity framework one to many in one table

[Table("Menus")]
public class Menus
{
    /// <summary>
    /// Table "Menus", ID
    /// </summary>
    private int _ID;
    [Key]
    [Display(Name = "ID")] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }

    /// <summary>
    /// Table "Menus", MenuName
    /// </summary>
    private string _MenuName;
    [Display(Name = "MenuName")]
    public string MenuName
    {
        get { return _MenuName; }
        set { _MenuName = value; }
    }

    /// <summary>
    /// Table "Menus", ParentID
    /// </summary>
    private int _ParentID;
    [Display(Name = "ParentID")]
    public int ParentID
    {
        get { return _ParentID; }
        set { _ParentID = value; }
    }
}

I have this table. 我有这张桌子。 And i want "one to many" in it on ParentID. 我想在ParentID上“一对多”。 I want choose parent id from list and want to do it by Entity framework or fluent api, but don't know them good. 我想从列表中选择父ID,并希望通过Entity Framework或流畅的api来实现,但是我不知道它们的好之处。

You would want to do something like this: 您可能想要执行以下操作:

[Table("Menus")]
public class Menus
{
    [Key]
    public int ID { get; set; }

    public string MenuName { get; set; }

    [ForeignKey("ParentMenu")]
    public int ParentID { get; set; }

    public virtual Menu ParentMenu { get; set; }

    public virtual List<Menu> ChildMenus { get; set; }
}

Everything work. 一切正常。 Thanks. 谢谢。 I delete all rows in my tables and then create migrations. 我删除表中的所有行,然后创建迁移。 But the property must be nullable: 但是该属性必须可以为空:

    public int? ParentID { get; set; }

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

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