C # Entity Framework - Beginner
The database relationship looks like this: http://i.imgur.com/954gPnl.png
I have a connector table called friendship that contains 2 values ββand a key id. This table describes that X is Y's friend, but Y may not be X's friend. So this is some kind of linear material.
I would like to simulate the same in Entity Framework, but I fail all the time because I get this error:
can cause loops or multiple cascading paths.
I made two tables in 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; }
}
source to share
I think you need to write your code like below and add correct relationship.
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; }
}
Also you need to add below code for relations between objects in your DB context file.
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);
}
source to share
In Entityframework, you cannot add more than one foreign key of the same class as the serum getting Error .. remove any of this ....
[ForeignKey("whoid")]
public virtual Person who { get; set; }
[ForeignKey("whomid")]
public virtual Person whom { get; set; }
I think this problem occurs when adding to sqlserver too
source to share