Entity Framework stores data in one-to-one associations

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

+6
source share
1 answer

You do not store the data incorrectly, but simply cannot work, because you defined a bi-directional dependency. A command can only be saved if it is associated with an already saved user, and a user can only be saved if it is associated with an existing command. You must make one relationship optional by specifying a foreign key property nullable (e.g. TeamId in User ):

 public class User { public int ID { get; set; } public string UserName { get; set; } public int? TeamID { get; set; } public virtual Team Team { get; set; } } 

Then you must first save the User object and then save the Team .

 User u = new User(); u.UserName = "farinha"; context.Users.Add(u); context.SaveChanges(); u.Team = new Team { Name = "Flour Power", OwnerID = u.ID }; context.SaveChanges(); 
+8
source

Source: https://habr.com/ru/post/887777/


All Articles