Entity Framework saving data in one-to-one associations -


i'm trying use foreign key association approach achieve one-to-one association in ef. in case there's association between user , team, , need navigation property in each of them. bumped problem when trying save data.

this models 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 dbcontext onmodelcreating(), instructed in blog post referenced 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 when adding data this:

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 this:

user u = new user(); u.username = "farinha"; u.team = new team("flour power"); context.users.add(u); context.savechanges(); 

i'm getting following error:

unable determine valid ordering dependent operations. dependencies may exist due foreign key constraints, model requirements, or store-generated values.

any idea of how solve this? saving data in wrong way?

thanks in advance

you not saving data wrong way cannot work because defined bidirectional dependency. team can saved if related saved user , user can saved if related existing team. must make 1 relation optional marking foreign key property nullable (for example 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 must save user entity first , can save 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(); 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -