Entity Framework: Model Contain A list(navigational properties) of three items of type= itself , giving error. (May be foreign key mapping error)
My Model looks like like this
public class User
{
public int ID { get; set; }
public string Name { get; set; }
/*Users who are following current user*/
public virtual ICollection<User> Followers { get; set; }
/*Users whom current user is following*/
public virtual ICollection<Us开发者_StackOverflow中文版er> Following { get; set; }
/*current user has ignored these users*/
public virtual ICollection<User> Ignores { get; set; }
}
To add data
User john = new User { Name = "john" };
User mary = new User { Name = "mary" };
User david = new User { Name = "david" };
john.Following = new List<User> { mary };
mary.Followers = new List<User> { john};
john.Ignores = new List<User> { david};
context.Users.Add(john);
context.Users.Add(mary);
context.Users.Add(david);
context.SaveChanges();
Doing this is giving error:
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
If i remove the propert Ignores
from User
Model its working perfect, but with ignores it doesn't.
I think there is some mapping thats need to be done, please suggest me how can i do this!!
The problem seems to be that EF does not know which two are a many-to-many and which one is a one-to-many. You could try explicitly stating these rather than relying on convention. Try overriding the OnModelCreating(DbModelBuilder)
method of the DbContext
class (if you are using DbContext).
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Entity<User>()
.HasMany(u => u.Ignores)
.WithReequired()
.HasForeignKey(u => u.ID);
mb.Entity<User>()
.HasMany(u => u.Followers)
.WithMany(u => u.Following);
// If you want to specify a table, use the following line:
// .Map(m => m.ToTable("CustomManyToManyTableName");
}
Notice: I made this up off the top of my head so don't rely on my syntax and such precisely, but it should be pretty close.
精彩评论