我应该如何首先使用EF代码为用户之间的友谊建模? [英] How should I model friendships between users with EF code first?

查看:70
本文介绍了我应该如何首先使用EF代码为用户之间的友谊建模?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图弄清楚如何使用Entity Framework(5)Code First来表示用户之间的友谊。我最初的想法是创建一个包含两个用户实例的引用的Friendship类,以便由单独的对象表示友谊。

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

当尝试通过EF迁移创建数据库时,由于SQL错误而陷入困境:

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.

推荐答案

经过更多的谷歌搜索后,我设法在SO上找到了类似的问题,并且那里有一种解决方案,至少使它毫无问题地进入了数据库。

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.

基本上,我将每个用户的外键添加到 Friendship 类中,使它们成为复合主键并配置了第二个外键不要在删除时级联。我最终使用了EF流利的配置。

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

这篇关于我应该如何首先使用EF代码为用户之间的友谊建模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆