EF核心自我引用多对多

时间:2018-07-30 08:40:49

标签: c# entity-framework .net-core

我有用户表,我想在2个用户之间添加名为UserFriend的连接。我进行了很多搜索,基本上尝试了许多不同的解决方案,但没有一个起作用。每当我遇到相同的错误:

  

在表'UserFriends'上引入FOREIGN KEY约束'FK_UserFriends_Users_Friend2Id'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

这是我的模特:

public class User
    {
        [Key]
        public Guid Id { get; set; }

        public string Username { get; set; }
        public string EmailAddress { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }

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

public class UserFriend
    {                        
        public User Friend1 { get; set; }
        public Guid Friend1Id { get; set; }

        public User Friend2 { get; set; }
        public Guid Friend2Id { get; set; }

        public bool Confirmed { get; set; }
        public DateTime Added { get; set; }
    }

这是DataContext中的代码:

modelBuilder.Entity<UserFriend>().HasKey(sc => new { sc.Friend1Id, sc.Friend2Id });            

            modelBuilder.Entity<UserFriend>()
                .HasOne(c => c.Friend1)
                .WithMany(c => c.FriendOf)
                .HasForeignKey(f => f.Friend1Id);                

            modelBuilder.Entity<UserFriend>()
                .HasOne(c => c.Friend2)
                .WithMany(c => c.Friends)
                .HasForeignKey(f => f.Friend2Id)
                .OnDelete(DeleteBehavior.Restrict);

1 个答案:

答案 0 :(得分:0)

将代码更改为以下代码,并删除其他已发布的行。

public class User
    {
        [Key]
        public Guid Id { get; set; }

        public string Username { get; set; }
        public string EmailAddress { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }

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

public class UserFriend
    {        

        public User Friend1 { get; set; }
        [ForeignKey("Friend1")]  
        public Guid? Friend1Id { get; set; }

        public User Friend2 { get; set; }
         [ForeignKey("Friend2")]
        public Guid? Friend2Id { get; set; }

        public bool Confirmed { get; set; }
        public DateTime Added { get; set; }
    }

 modelBuilder.Entity<User>();
 modelBuilder.Entity<UserFriend>();