你可以用反射来做到这一点。以下是查找所有相关集合的扩展方法。如果你的所有实体都实现了一些标准接口,你将能够制作一个类似的方法来找到非集合的导航属性(实现你的接口)。
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;
}
}
这应该添加当前对象的导航属性
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;
}
}
}
我很少用'dynamic'但我有点惊讶的是'typeof运算(IEnumerable的).IsAssignableFrom'是有效的。这基本上是否解析为“IEnumerable