同班自学

时间:2019-09-19 01:54:16

标签: asp.net-core entity-framework-core

我有一个名为“ ApplicationUser”的类,该类具有一个名为followers的属性,该属性与以下类型相同:

public class ApplicationUser : IdentityUser<Guid>
{
    public string FcmToken { get; set; }
    public bool NotificationEnabled { get; set; }
    public List<ApplicationUser> Followers { get; set; }
    public List<ApplicationUser> Follows { get; set; }
}

在我的ApplicationDbContext中,方法“ OnModelCreating”如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ApplicationUser>().HasMany(s => s.Followers).WithMany().Map(m =>
        {

        });           

        base.OnModelCreating(modelBuilder);
    }

错误在于.WithMany()中,它显示“应用程序用户不包含WithMany的定义”

我一直在看有关自引用的教程,这是使用Entity Framework 6的方法,但是我没有找到使用.net core 2.2的方法。 任何帮助都会对我有帮助。谢谢,谢谢。

1 个答案:

答案 0 :(得分:0)

EF Core实际上并不支持多对多关系。解决方法是使用中间实体来连接这两个方面,以便在关系的每一端与该中间类之间存在一对多的关系。换句话说:

public class ApplicationUserFollower
{
    public ApplicationUser Follower { get; set; }
    public ApplicationUser Followee { get; set; }
}

然后在ApplicationUser

public class ApplicationUser : IdentityUser
{
    ...

    public ICollection<ApplicationUserFollower> Following { get; set; }
    public ICollection<ApplicationUserFollower> Followers { get; set; }
}

最后,在您流畅的配置中:

modelBuilder.Entity<ApplicationUser>().HasMany(s => s.Following).WithOne(x => x.Follower);
modelBuilder.Entity<ApplicationUser>().HasMany(s => s.Followers).WithOne(x => x.Followee);