c# - "NullReferenceException was unhandled by user code" when trying to retrive a navigation property using entry.GetDatabaseValues().ToObject() -
i have folloiwng action methods:-
[httppost] [validateantiforgerytoken] public actionresult edit(rack rack) { try { if (modelstate.isvalid) { repository.insertorupdaterack(rack); repository.save(); return redirecttoaction("index"); } } catch (dbupdateconcurrencyexception ex) { var entry = ex.entries.single(); var databasevalues = (rack)entry.getdatabasevalues().toobject(); var clientvalues = (rack)entry.entity; if (databasevalues.ru != clientvalues.ru) modelstate.addmodelerror("ru", "current value: " + databasevalues.ru); if (databasevalues.datacenterid != clientvalues.datacenterid) modelstate.addmodelerror("datacenterid", "current value: " + databasevalues.datacenter.name); if (databasevalues.zoneid != clientvalues.zoneid) modelstate.addmodelerror("zoneid", "current value: " + databasevalues.zone.name);
but if dbupdateconcurrncy exception raised null reference exception on databasevalues.datacenter.name
& databasevalues.zone.name
. seems can not access 2 navigation properties (datacenter & rack) getdatabase().toobject
.any idea how can solve issue?
i've given answer here copying here others' convenience question came on first page of google search:
i'm leaving here still stumbles upon when trying handle concurrency issues or like.
the toobject
method doesn't populate navigational properties of entity form database when populates entity latest database values. somehow acceptable navigational properties may have additions/deletions should handled manually. bear in mind entity detached
i haven't been able find way populate values automatically ef. have use 'getvalue` method each property interested in , populate them yourself.
here pseudo-code solution:
dbentityentry entry = context.entry(yourentity); //gets latest values of entity database var propertyvalues = entry.getdatabasevalues(); //fills entity object database values(except navigational properties) dynamic newentity = propertyvalues.toobject(); //manually loading needed navigational properties , handling add/removes. foreach (var prop in propertyvalues.propertynames) { //either collection<int> or int. var idofreferencedelement = propertyvalues.getvalue<int>(foreignkeyfield); //remember handle add/removes too. newentity.[thepropertyyouknowexist] = context.[thedbset].local.find(idofreferencedelement); }
Comments
Post a Comment