如何将模型 属性 与 ASP.NET MVC 中的同一模型相关联?

How to relate model property to same model in ASP.NET MVC?

有时,您想存储谁注册或创建了用户帐户。它要么是用户注册 himself/herself 要么是其他用户帐户注册了他,例如管理员帐户。所以,用户 table 会是这样的:

public class User : Identity
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    // this is the part that I'd to relate to the same model
    [ForeignKey("Id")]
    public virtual User RegisteredBy { get; set; }
}

使用数据注释或 Fluent API,您如何将 User.RegisteredBy 与 User.Id 联系起来?

提前致谢!

类似于您的 class

public class User : Identity
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }

    // this is the self referential part
    public int? RegisteredById  { get; set; }
    public virtual User RegisteredBy { get; set; }
    public virtual ICollection<User> RegisteredUsers { get; set; }
}

然后在您的 DbContext

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
        .HasOptional(x => x.RegisteredBy)
        .WithMany(x => x.RegisteredUsers)
        .HasForeignKey(x => x.RegisteredById);
}

这是未经测试的,但我不久前在一个项目中做了类似的事情并且效果很好。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
                .HasOptional(c => c.RegisteredBy)
                .WithMany()
                .HasForeignKey(c => c.RegisteredById);
}

您可以使用上面的 Fluent Api 代码,您的 class 应该如下所示

public class User : Identity
{
 public int Id { get; set; }
 public string UserName { get; set; }
 public string Email { get; set; }
 public string Name { get; set; }

 public int? RegisteredById { get; set; }                

 public User RegisteredBy { get; set; }
}