简体   繁体   中英

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. I want choose parent id from list and want to do it by Entity framework or fluent api, but don't know them good.

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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