C#实体框架 - 初学者

3
目前数据库关系如下所示:http://i.imgur.com/954gPnl.png 我有一个连接器表叫做“friendship”,它包含2个值和一个键ID。这张表描述了X和Y是朋友,但Y可能不会成为X的朋友。所以这是一种线性的东西。
我想在实体框架中建立同样的模型,但我总是失败,因为我遇到了这个错误:

可能会导致循环或多重级联路径。

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

请看这里:https://dev59.com/Z4Xca4cB1Zd3GeqPEi_L - jlvaquero
2个回答

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

您需要在您的DB上下文文件中添加以下代码,以建立实体之间的关系。
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);   




}

一旦我尝试保存更改,调试器就会显示异常:“INSERT语句与FOREIGN KEY约束“FK_dbo.Friendships_dbo.People_whoid”冲突。” - original.roland
这背后的原因是,当您在子表中插入记录时,引用列的值在父表上尚不存在。 - Dharmesh

0
在Entity Framework中,您不能添加同一类的多个外键,这就是为令它出现错误的原因...请移除其中任何一个。
[ForeignKey("whoid")]
public virtual Person who { get; set; }

[ForeignKey("whomid")]
public virtual Person whom { get; set; }

我认为当在SQL Server中添加时,您也会遇到这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接