【问题标题】:How to implement a self-referencing many-to-many relations in .NET EF Core如何在 .NET EF Core 中实现自引用多对多关系
【发布时间】:2021-10-29 09:35:02
【问题描述】:

我正在制作一个作为社交网络的 Web 应用程序,但在 EF Core(代码优先,SQL Server)创建模型的阶段遇到了问题。

我需要为用户添加添加好友的功能。所以,我试图建立一个像“自引用多对多”这样的连接。我看到了如何通过在类中创建一个额外的数组来解决这个问题,但是有没有办法绕过这个“拐杖”?

这是我的User 课程代码:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // ... Other properties

    public ICollection<UserFriend> Friends { get; set; }
}

这是UserFriend 类:

public class UserFriend
{
    public int UserId { get; set; }
    public User User { get; set; }

    public int FriendId { get; set; }
    public User Friend { get; set; }
}

这也是我的DbContext 及其OnModelCreating 设置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<UserFriend>()
                .HasKey(i => new { i.UserId, i.FriendId });

    modelBuilder.Entity<UserFriend>()
                .HasOne(c => c.User)
                .WithMany(w => w.UserFriends)
                .HasForeignKey(f => f.UserId)
                .OnDelete(DeleteBehavior.Restrict);

    modelBuilder.Entity<UserFriend>()
                .HasOne(c => c.Friend)
                .WithMany(w => w.UserFriends)
                .HasForeignKey(f => f.FriendId)
                .OnDelete(DeleteBehavior.Restrict);
}

【问题讨论】:

  • 拥有公共 ICollection 朋友 { 得到;放; } 在你的班级?
  • 这样不行,因为你需要建立表之间的关系,结果我们有一个自引用的多对多关系
  • 此方法在 EF Core 中不起作用

标签: c# .net sql-server database entity-framework-core


【解决方案1】:

您在 User 中的收藏应该是 Friend 类型而不是 UserFriend。也让它虚拟化:

public virtual ICollection<Friend> Friends {get;set;}

【讨论】:

  • 对不起,我把“朋友”这个名字弄错了,但显示虚拟机无论如何都不起作用。
猜你喜欢
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 2017-09-08
  • 1970-01-01
相关资源
最近更新 更多