I am trying to use a foreign key interaction method to achieve one-to-one association in EF. In my case, there is a connection between the user and the team, and I need the navigation property in each of them. While trying to save data, I encountered a problem.
Here's what the models look like:
public class Team { public int ID { get; set; } public string Name { get; set; } public int OwnerID { get; set; } public virtual User Owner { get; set; } } public class User { public int ID { get; set; } public string UserName { get; set; } public int TeamID { get; set; } public virtual Team Team { get; set; } }
I added these bits to DbContext OnModelCreating() , as indicated in the blog post mentioned above:
modelBuilder.Entity<User>() .HasRequired(u => u.Team) .WithMany() .HasForeignKey(u => u.TeamID); modelBuilder.Entity<Team>() .HasRequired(t => t.Owner) .WithMany() .HasForeignKey(t => t.OwnerID) .WillCascadeOnDelete(false);
And now, adding such data:
User u = new User(); u.UserName = "farinha"; Team t = new Team("Flour Power"); u.Team = t; t.Owner = u; context.Users.Add(u); context.Teams.Add(t); context.SaveChanges();
or even so:
User u = new User(); u.UserName = "farinha"; u.Team = new Team("Flour Power"); context.Users.Add(u); context.SaveChanges();
I get the following error:
It is not possible to determine the actual ordering for dependent operations. dependencies may exist due to foreign key constraints, model requirements, or store values.
Any idea how to solve this? Am I saving data wrong?
Thanks in advance
source share