2013-05-07 181 views
3

我有以下的通用代码更新断开连接的实体:如果我的实体包含导航属性实体框架 - 附加实体 - 附加导航属性?

public T UpdateItem(T entity) 
{ 
    this._dbSet.Attach(entity); 
    this._dbContext.Entry(entity).State = System.Data.EntityState.Modified; 

    this._dbContext.SaveChanges(); 

    return entity; 
} 

,那些没有得到重视,并设置为修改。有没有一种方法可以改变这种通用方法来附加并设置为修改过的所有导航属性?

回答

5

你可以用反射来做到这一点。以下是查找所有相关集合的扩展方法。如果你的所有实体都实现了一些标准接口,你将能够制作一个类似的方法来找到非集合的导航属性(实现你的接口)。

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; 
     } 
    } 
} 
+0

我很少用'dynamic'但我有点惊讶的是'typeof运算(IEnumerable的).IsAssignableFrom'是有效的。这基本上是否解析为“IEnumerable ”,还是在评估过程中神奇地用'prop.PropertyType'替代动态? – xr280xr 2017-08-16 17:13:29