简体   繁体   中英

EF Core self referencing many to many

I have User table and I'd like to add connection called UserFriend between 2 users. I've searched a lot and basicly tried many different solutions and none of them worked. Everytime I get same error:

Introducing FOREIGN KEY constraint 'FK_UserFriends_Users_Friend2Id' on table 'UserFriends' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Here are my models:

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

And here's code in 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);

Change your code to below and remove the other lines you have posted.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM