【问题标题】:How to relate model property to same model in ASP.NET MVC?如何将模型属性与 ASP.NET MVC 中的同一模型相关联?
【发布时间】:2015-05-22 08:09:39
【问题描述】:

有时,您想存储谁注册或创建了用户帐户。要么是用户自己注册,要么是其他用户帐户注册了他,例如管理员帐户。所以,用户表应该是这样的:

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 关联起来?

提前致谢!

【问题讨论】:

    标签: asp.net-mvc entity-framework data-annotations foreign-key-relationship ef-fluent-api


    【解决方案1】:

    像你班上的东西

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

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

    【讨论】:

    • 谢谢!看起来很有希望。我得试试这个。
    【解决方案2】:
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
                    .HasOptional(c => c.RegisteredBy)
                    .WithMany()
                    .HasForeignKey(c => c.RegisteredById);
    }
    

    你可以使用上面的 Fluent Api 代码,你的类应该是这样的

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

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多