Detach之后的POCO如何Attach以及LoadProperty
public void Attach(string entityName, object entity, params string[] navigationProperties)
{
ObjectContext objectContext = ((IObjectContextAdapter)_Context).ObjectContext;
objectContext.AttachTo(entityName, entity); //把detach的entity attach到ObjectContext
objectContext.ObjectStateManager.GetObjectStateEntry(entity).SetModified(); //把entity的状态从Unchanged变为Modified
foreach (string navigationProperty in navigationProperties) //如果有属性要访问,那么可以一起load
{
objectContext.LoadProperty(entity, navigationProperty);
}
}
改进版本:
public void Attach<TEntity>(object entity, params Expression<Func<TEntity, object>>[] navigationProperties)
{
ObjectContext objectContext = ((IObjectContextAdapter)_Context).ObjectContext;
objectContext.AttachTo(entity.GetType().Name, entity);
objectContext.ObjectStateManager.GetObjectStateEntry(entity).SetModified();
foreach (Expression<Func<TEntity, object>> navigationProperty in navigationProperties)
{
objectContext.LoadProperty(entity, navigationProperty.Body.Type.Name);
}
}