实体框架 - 存储关于子关系的父引用(一个 - >多个)

时间:2012-10-31 04:57:38

标签: c# entity-framework entity-framework-5

我有这样的设置:

[Table("tablename...")]
public class Branch
{
    public Branch()
    {
        Users = new List<User>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public List<User> Users { get; set; }
}

[Table("tablename...")]
public class User
{
    [Key]
    public int Id {get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    [ForeignKey("ParentBranch")]
    public int? ParentBranchId { get; set; } // Is this possible?
    public Branch ParentBranch { get; set; } // ???
}

用户是否可以知道它属于哪个父分支?上面的代码不会填充ParentBranch。

Entity Framework 5.0版 .NET 4.0 C#

1 个答案:

答案 0 :(得分:2)

尝试虚拟导航属性

[Table("tablename...")]
public class Branch
{
    public Branch()
    {
        Users = new List<User>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<User> Users { get; set; }
}

[Table("tablename...")]
public class User
{
    [Key]
    public int Id {get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    [ForeignKey("ParentBranch")]
    public int? ParentBranchId { get; set; } // Is this possible?
    public virtual Branch ParentBranch { get; set; } // ???
}