【发布时间】:2015-11-09 09:14:05
【问题描述】:
我想创建一个简单的朋友列表,每行有两个 id(用户 id 和朋友 id),都引用各自用户个人资料中的“id”字段
|relationId|userId|friendId|
如果双方向对方发送友谊请求,用户就会成为朋友。例如:
|1|2|4|
|1|4|2| //id 为 2 和 4 的用户是好友
到目前为止,设置外键对我来说很容易。当我必须为同一张表设置两个外键时,事情变得更加困难。我遇到了不同的错误,我希望修复这些错误,然后重新调整我的代码,最后我觉得我过于复杂了。
UserProfile 模型:
[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
}
这给了我以下例外:
在表“Friends”上引入 FOREIGN KEY 约束“Friends_User”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
我搜索了类似的问题,我看到了许多外键的示例,但是,我无法找到任何两个字段链接到同一个表的示例。
【问题讨论】:
标签: c# sql-server asp.net-mvc entity-framework