How should I model friendships between users with EF code first?

前端 未结 2 1828
逝去的感伤
逝去的感伤 2021-01-20 01:06

I\'m tring to figure out how to represent friendships between users with Entity Framework (5) Code First. My initial idea was to create a class Friendship which contains ref

2条回答
  •  醉酒成梦
    2021-01-20 01:50

    I managed to find a similar question on SO after some more googling, and there's a solution there that at least made it into the database without problems.

    Basically, I added foreign keys per user to the Friendship class, made them a composite primary key and configured the second foreign key not to cascade on delete. I ended up using EF fluent configuration.

    public class Friendship
    {
        public virtual int UserId1 { get; set; }
        public virtual int UserId2 { get; set; }
        public virtual User User1 { get; set; }
        public virtual User User2 { get; set; }
        public DateTime since;
    }
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        ...
        modelBuilder.Entity().HasKey(f => new { f.UserId1, f.UserId2 });
        modelBuilder.Entity()
          .HasRequired(f => f.User1)
          .WithMany()
          .HasForeignKey(f => f.UserId1);
        modelBuilder.Entity()
            .HasRequired(f => f.User2)
            .WithMany()
            .HasForeignKey(f => f.UserId2)
            .WillCascadeOnDelete(false);
    }
    

提交回复
热议问题