问题
I have the following generic code to update a disconnected entity:
public T UpdateItem(T entity)
{
this._dbSet.Attach(entity);
this._dbContext.Entry(entity).State = System.Data.EntityState.Modified;
this._dbContext.SaveChanges();
return entity;
}
If my entity contains navigation properties, those do not get attached and set to modified. Is there a way I can change this generic method to attach and set to modified, all navigation properties as well?
回答1:
You can do it with reflection. Here's an extension method to find all the related collections. If all of your Entities implement some standard interface you'll be able to make a similar method to find the non collection navigation properties (that implement your interface).
public static class ContextExtensions
{
public static IEnumerable<IEnumerable<dynamic>> GetCollections(this object o)
{
var result = new List<IEnumerable<dynamic>>();
foreach (var prop in o.GetType().GetProperties())
{
if (typeof(IEnumerable<dynamic>).IsAssignableFrom(prop.PropertyType))
{
var get = prop.GetGetMethod();
if (!get.IsStatic && get.GetParameters().Length == 0)
{
var enumerable = (IEnumerable<dynamic>)get.Invoke(o, null);
if (enumerable != null) result.Add(enumerable);
}
}
}
return result;
}
}
This should add the current objects navigation properties
var collections = entity.GetCollections();
foreach (var collection in collections)
{
foreach (var r in collection)
{
if (_this._dbSet.Entry(r).State == System.Data.EntityState.Detached)
{
this._dbSet.Attach(r);
this._dbContext.Entry(r).State = System.Data.EntityState.Modified;
}
}
}
来源:https://stackoverflow.com/questions/16419773/entity-framework-attaching-entities-attach-navigation-properties