How do I save a NavigationProperty on an Entity from a different context?
I have two database tables, one for Events and one for RecurrenceRules. Events have a FK that points to a RecurrenceRuleID.
All I want to do is Save an Event AND it's Recurrence rule from a new context, but I can't seem to accomplish this. What am I missing??
using (var context = new ScheduledEventEntities())
{
if (obj.EntityKey == null)
{
context.AddObject(obj.EntityKey.EntitySetName, obj);
}
else
{
var existingObject = context.Events.FirstOrDefault(p => p.Ident == obj.Ident);
context.ApplyCurrent开发者_JS百科Values<Event>(obj.EntityKey.EntitySetName, obj);
// How do I save obj.RecurrenceRule?
}
context.SaveChanges();
}
I would try it this way:
// ...
var existingObject = context.Events.Include("RecurrenceRule")
.FirstOrDefault(p => p.Ident == obj.Ident);
context.ApplyCurrentValues<Event>(obj.EntityKey.EntitySetName, obj);
// 1st case: Relationship to RecurrenceRule has been removed or didn't exist
if (obj.RecurrenceRule == null)
existingObject.RecurrenceRule = null;
// 2nd case: Relationship to RecurrenceRule must be set or updated
else
{
// relationship has changed
if (existingObject.RecurrenceRule == null ||
obj.RecurrenceRule.Id != existingObject.RecurrenceRule.Id)
{
var existingRecurrenceRule = context.RecurrenceRule
.SingleOrDefault(r => r.Id == obj.RecurrenceRule.Id);
if (existingRecurrenceRule != null) // RecurrenceRule exists in DB
{
// Update scalar values
context.ApplyCurrentValues<RecurrenceRule>(
obj.RecurrenceRule.EntityKey.EntitySetName, obj.RecurrenceRule);
}
else // RecurrenceRule does not exist in DB
{
// nothing to do, SaveChanges will recognize new RecurrenceRule
// and create INSERT statement
}
// set new relationship
existingObject.RecurrenceRule = obj.RecurrenceRule;
}
else // same relationship: just update scalar values
{
// Update scalar values
context.ApplyCurrentValues<RecurrenceRule>(
obj.RecurrenceRule.EntityKey.EntitySetName, obj.RecurrenceRule);
}
}
// ...
The problem is indeed that ApplyCurrentValues
only cares about updating scalar properties but not navigation properties, so you have to handle updating the navigation properties yourself. (Unfortunately updating detached object graphs leads almost always to such tedious code because there is no built-in mechanism in Entity Framework to do this work for you.)
精彩评论