entity framework - "The property $propertyName is part of the object's key information and cannot be modified." on navigation property with shared composite key -
to preface question: problem not because i'm directly setting key property in model entity object (which cause of issue in other search results same exception message).
i'm making heavy use of composite keys in application, here's simplified version of current db schema (key fields in *asterisks*
):
tenants( *tenantid*, ... ) categories( *tenantid*, *categoryid*, ... ) documents( *tenantid*, *documentid*, categoryid, ... )
the documents
table has fk relationships both tenants
, categories
, both using same documents.tenantid
column. documents.categoryid
column null
able.
when this, exception:
tenant tenant = gettenant( 123 ); document doc = tenant.documents.first(); category newcategory = new category(); newcategory.tenantid = 123; dbcontext.categories.add( newcategory ); doc.category = newcategory; <-- exception thrown on line, without calling dbcontext.savechanges() @ all.
i believe exception because setting category
on document
instance causes tenantid
property set indirectly ef (because it's part of documents -> categories
fk association.
what solution?
workaround update
i'm able hack creating new category
entities saving them, identity
values back, setting document
properties directly:
tenant tenant = gettenant( 123 ); document doc = tenant.documents.first(); category newcategory = new category(); newcategory.tenantid = 123; dbcontext.categories.add( newcategory ); dbcontext.savechanges(); doc.categoryid = newcategory.categoryid dbcontext.savechanges();
but ideally i'd work in single call savechanges()
, using entity model navigation properties instead of scalar attribute properties.
for initial problem, worked-around using "workaround update" posted original posting.
however problem happened again different entity type (again, composite key involved in foreign-key) , noticed ef throws exception if call dbcontext.entry()
on entity in graph while new entity in added
state - not throw exception again if re-call entry()
or savechanges()
, , in fact saves new entities correctly in spite of initial exception - i'm thinking might bug in ef.
here's have now:
tenant tenant = gettenant( 123 ); document doc = tenant.documents.first(); category newcategory = new category(); newcategory.tenantid = 123; dbcontext.categories.add( newcategory ); doc.categoryid = newcategory.categoryid try { dbcontext.entry( doc ); } catch(invalidoperationexception) { } dbcontext.savechanges();
it's ugly, works - , avoids having call savechanges
twice.
Comments
Post a Comment