How should I model friendships between users with

2019-02-24 08:25发布

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 references to two User instances, so that friendships are represented by separate objects.

public class Friendship
{
    public virtual int Id { get; set; }
    [Required]
    public virtual UserProfile User1 { get; set; }
    [Required]
    public virtual UserProfile User2 { get; set; }
    [Required]
    public virtual DateTime Since { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    [Required]
    public string UserName { get; set; }
}

When trying to create the database via EF Migrations, however, I'm stumped due to a SQL error:

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

Suggestions as to how to solve this problem would be very welcome.

2条回答
何必那么认真
2楼-- · 2019-02-24 08:49

You could define the foreign keys yourself or remove cascade delete, depending on your scenario. See this related question : Entity Framework Code First: FOREIGN KEY constraint may cause cycles or multiple cascade paths

查看更多
Explosion°爆炸
3楼-- · 2019-02-24 09:02

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<Friendship>().HasKey(f => new { f.UserId1, f.UserId2 });
    modelBuilder.Entity<Friendship>()
      .HasRequired(f => f.User1)
      .WithMany()
      .HasForeignKey(f => f.UserId1);
    modelBuilder.Entity<Friendship>()
        .HasRequired(f => f.User2)
        .WithMany()
        .HasForeignKey(f => f.UserId2)
        .WillCascadeOnDelete(false);
}
查看更多
登录 后发表回答