You can try this as follows:
public class User { public int Id { get; set; } public ICollection<FriendRequest> FriendRequests { get; set; } } public class FriendRequest { public int UserId { get; set; } public int FriendId { get; set; } public DateTime RequestDate { get; set; } public User User { get; set; } public User Friend { get; set; } }
Mapping with the Fluent API:
modelBuilder.Entity<User>() .HasMany(u => u.FriendRequests) .WithRequired(f => f.User) .HasForeignKey(f => f.UserId); modelBuilder.Entity<FriendRequest>() .HasKey(f => new { f.UserId, f.FriendId }); modelBuilder.Entity<FriendRequest>() .HasRequired(f => f.Friend) .WithMany() .HasForeignKey(f => f.FriendId);
Due to the RequestDate property in the link table, you cannot match this as a many-to-many relationship. Instead, you need two one-to-many relationships, as shown above.
You may need to disable cascading deletion, I'm not sure. You can do this by adding .WillCascadeOnDelete(false) at the end of two one-to-many comparisons.
Edit
To your comment: If you remove the RequestDate column, you can create your own model with a many-to-many relationship. In this case, you do not need the FriendRequest object:
public class User { public int Id { get; set; } public ICollection<User> FriendRequests { get; set; } }
Mapping with the Fluent API:
modelBuilder.Entity<User>() .HasMany(u => u.FriendRequests) .WithMany() .Map(m => { m.ToTable("FriendRequests"); m.MapLeftKey("UserId"); m.MapRightKey("FriendId"); });
source share