var johnCarter = new Movie() { Title = "John Carter" };johnCarter.DirectorId = andrewStantonId;context.Movies.Add(johnCarter);//after it's added, change the status of the referencecontext.Entry(johnCarter.Director).State = EntityState.Unchanged;context.SaveChanges();
var johnCarter = new Movie() { Title = "John Carter" };johnCarter.DirectorId = andrewStantonId;context.Movies.Add(johnCarter);//after it's added, change the status of the referenceMarkNavigationPropertiesUnchanged(johnCarter);context.SaveChanges();
private static void MarkNavigationPropertiesUnchanged<T>(DbContext context, T entity) where T : class { var objectContext = ((IObjectContextAdapter)context).ObjectContext; var objectSet = objectContext.CreateObjectSet<T>(); var elementType = objectSet.EntitySet.ElementType; var navigationProperties = elementType.NavigationProperties; //the references var references = from navigationProperty in navigationProperties let end = navigationProperty.ToEndMember where end.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne || end.RelationshipMultiplicity == RelationshipMultiplicity.One select navigationProperty.Name; //NB: We don't check Collections. EF wants to handle the object graph. var parentEntityState = context.Entry(entity).State; foreach (var navigationProperty in references) { //if it's modified but not loaded, don't need to touch it if (parentEntityState == EntityState.Modified && !context.Entry(entity).Reference(navigationProperty).IsLoaded) continue; var propertyInfo = typeof(T).GetProperty(navigationProperty); var value = propertyInfo.GetValue(entity, null); context.Entry(value).State = EntityState.Unchanged; } }
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.