此时数据库关系如下所示: http://i.imgur.com/954gPnl.png
我有一个名为friendship的连接器表,它包含2个值和一个密钥ID。这个表描述了X个朋友Y,但Y可能不是X的朋友。所以这是某种线性的东西。
我想在Entity Framework中对其进行建模,但我一直都会失败,因为我收到了这个错误:
可能导致循环或多个级联路径。
我在EF制作了两张桌子:
class Friendship
{
[Key]
public int id { get; set; }
public int whoid { get; set; }
public int whomid { get; set; }
[ForeignKey("whoid")]
public virtual Person who { get; set; }
[ForeignKey("whomid")]
public virtual Person whom { get; set; }
}
class Person
{
[Key]
public int id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string name { get; set;}
public string city { get; set; }
public string street { get; set; }
public string hnum { get; set; }
public string bday { get; set; }
[InverseProperty("who")]
public virtual List<Friendship> wholist { get; set; }
[InverseProperty("whom")]
public virtual List<Friendship> whomlist { get; set; }
}
答案 0 :(得分:2)
我认为您需要编写如下代码并添加正确的关系。
class Friendship
{
[Key]
public int id { get; set; }
[ForeignKey("who")]
public int whoid { get; set; }
[ForeignKey("whom")]
public int whomid { get; set; }
public virtual Person who { get; set; }
public virtual Person whom { get; set; }
}
class Person
{
[Key]
public int id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string name { get; set;}
public string city { get; set; }
public string street { get; set; }
public string hnum { get; set; }
public string bday { get; set; }
[InverseProperty("who")]
public virtual List<Friendship> wholist { get; set; }
[InverseProperty("whom")]
public virtual List<Friendship> whomlist { get; set; }
}
此外,您还需要为数据库上下文文件中的实体之间的关系添加以下代码。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Friendship>()
.HasRequired(e => e.who)
.WithMany(t => t.wholist)
.HasForeignKey(e => e.whoid)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Friendship>()
.HasRequired(e => e.whom)
.WithMany(t => t.whomlist)
.HasForeignKey(e => e.whomid)
.WillCascadeOnDelete(false);
}
答案 1 :(得分:0)
在Entityframework中,你不能添加多个相同Class的外键,因为它会收到错误..删除任何一个....
[ForeignKey("whoid")]
public virtual Person who { get; set; }
[ForeignKey("whomid")]
public virtual Person whom { get; set; }
我认为在sqlserver中添加时也会遇到这个问题