c# - Entity Framework Core: How to add a composite object? -
there following composite object, example:
public class parent { [key] public int id { get; set; } [foreignkey("childrefid")] public guid childid { get; set; } public child child { get; set; } } public class child { [key] public guid id { get; set; } [foreignkey("parentrefid")] public int parentid { get; set; } public parent parent { get; set; } }
parent
, child
has one-to-one relation:
modelbuilder.entity<parent>() .hasone(parent => parent.child) .withone(child => child.parent) .willcascadeondelete();
i try create new parent
child
, save in db:
var parent = new parent { child = new child() }; dbcontext.parents.add(parent); dbcontext.savechanges(); //<-- exception!
...and following exception:
system.data.sqlclient.sqlexception: insert statement conflicted foreign key constraint "fk_parent_child_childid". conflict occurred in database "mydatabase", table "dbo.child", column 'id'.
if use db context create child works fine:
var child = dbcontext.childs.add(new child()); var parent = new parent { child = child }; dbcontext.parents.add(parent); dbcontext.savechanges(); //<-- works fine
question #1: can add new entities nested collections without using context create it. not works one-to-one relation. example:
var parent = new parent(); parent.grandparents.add(new grandparent(); dbcontext.parents.add(parent); dbcontext.savechanges(); //<-- works fine , parent 1 new grandparent created!
why?
question #2: please, describe me wrong , how can save new parent child without context create child (like nested collections)?
thank you!
this error occurring beta-8
version of ef. after updated ef rc1-final
version error disappeared. may explained there no graph tracking on beta-8
version yet.
you can find more detailed information here.
Comments
Post a Comment