我想创建一个简单的好友列表,每行有两个 ID(用户 ID 和好友 ID),都引用各自用户个人资料中的“id”字段
|relationId|userId|friendId|
如果双方都向对方发送好友请求,则用户成为好友。例如:
|1|2|4|
|1|4|2|//id为2和4的用户是好友
到目前为止,设置外键对我来说很容易。当我必须为同一个表设置两个外键时,事情变得更难了。我遇到了不同的错误,我希望修复这些错误,然后重新调整我的代码,最后我觉得我过于复杂了。
用户文件模型:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
好友模型:
[Table("Friends")]
public class Friends
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RelationId { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public UserProfile User { get; set; } // works with one foreign key
public int FriendId { get; set; }
[ForeignKey("FriendId")]
public UserProfile Friend { get; set; } // doesn't work when I add this one
}
这给了我以下异常:
Introducing FOREIGN KEY constraint 'Friends_User' on table 'Friends' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
我搜索过类似的问题,我见过很多外键的例子,但是,我找不到任何两个字段链接到同一个表的例子。
请您参考如下方法:
在这种情况下,异常消息告诉您有多个具有级联操作的外键。这是因为对于必需的关联,EF 默认会在删除时实现级联。
因此您必须从关联中删除至少一个级联操作。这个没有数据注释,所以你应该使用流畅的映射,例如:
modelBuilder.Entity<Friends>()
.HasRequired(p => p.User)
.WithMany()
.HasForeignKey(p => p.UserId)
.WillCascadeOnDelete(true);
modelBuilder.Entity<Friends>()
.HasRequired(p => p.Friend)
.WithMany()
.HasForeignKey(p => p.FriendId)
.WillCascadeOnDelete(false);
(在 DbContext 的覆盖 OnModelCreating 中)。
使用此映射时,您不再需要 ForeignKey 属性。
