I am using the following code snippet to save a modified entity in my repository
object id1 = item.GetProperty("Id");
T originalEntity = dbSet.Find(id1); // but this doesnt update navigation properties
((DbContext)context).Entry(originalEntity).CurrentValues.SetValues(item);
navProps = GetNavigationProperties(originalEntity);
foreach (PropertyInfo navProp in navProps)
{
//Set originalEntity prop value to modifiedEntity value
var newval = (LoggedEntity)navProp.GetValue(item);
object entity = null;
if (newval != null)
{
Type tp = navProp.PropertyType;
DbSet entities = ((DbContext)context).Set(tp);
entity = entities.Find(newval.Id);
}
navProp.SetValue(originalEntity, entity);
}
which calls
public List<PropertyInfo> GetNavigationProperties(T entity)
{
Type t = entity.GetType();
ObjectContext objectContex = ((IObjectContextAdapter)((DbContext)context)).ObjectContext;
EntityType elementType = objectContex.CreateObjectSet<T>().EntitySet.ElementType;
var properties = new List<PropertyInfo>();
Type entityType = entity.GetType();
foreach (NavigationProperty navigationProperty in elementType.NavigationProperties)
{
PropertyInfo prop = entityType.GetProperty(navigationProperty.Name);
properties.Add(prop);
}
return properties;
}
However I have a problem when I want to set the navigation property to null. The changes simply don't save.
The answer is explained in this question
Which points out that the navigation properties need to be eager loaded.
How do I modify my GetNavigationProperties procedure to eager load?