TryUpdateModel,实体框架以及为什么更新不起作用?

时间:2011-08-17 13:44:59

标签: asp.net-mvc entity-framework

我使用Entity Framework来处理我的数据库,而且我搜索了很多,我遇到了一些关于更新我的实体的解决方案,这里是更新实体代码的扩展方法:

public static void AttachUpdated(this ObjectContext context, EntityObject objectDetached)
{
   if (objectDetached.EntityState == EntityState.Detached)
   {
      object currentEntityInDb = null;

      if (context.TryGetObjectByKey(objectDetached.EntityKey, out currentEntityInDb))
      {
         context.ApplyPropertyChanges(objectDetached.EntityKey.EntitySetName, objectDetached);

         //(CDLTLL)Apply property changes to all referenced entities in context
         //Custom extensor method
         context.ApplyReferencePropertyChanges((IEntityWithRelationships)objectDetached,
                                               (IEntityWithRelationships)currentEntityInDb); 
       }
       else
       {
           throw new ObjectNotFoundException();
       }
    }
}

public static void ApplyReferencePropertyChanges(this ObjectContext context,
                                                 IEntityWithRelationships newEntity,
                                                 IEntityWithRelationships oldEntity)
{
   foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds())
   {
      var oldRef = relatedEnd as EntityReference;

      if (oldRef != null)
      {
         // this related end is a reference not a collection
         var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference;

         oldRef.EntityKey = newRef.EntityKey;
      }
   }
}

以下是保存或添加新对象的代码:

public void save (Category obj)
{
    OurWebSiteEntities en = new OurWebSiteEntities();

    if (obj.CategoryID == -1)
    {
       en.AddToCategories(obj);
    }
    else
       en.AttachUpdated(obj);

    en.SaveChanges();
}

最后这个代码用于在asp.net mvc中更新我的类别实体:

if (cat.Category.CategoryID == -1)
{
   // it is a new category
   // and needs some property initialization   
}
else
   catItem = _categoryRepo.Items.FirstOrDefault(x => x.CategoryID == cat.Category.CategoryID);

TryUpdateModel(catItem, "Category");

_categoryRepo.Save(catItem);

但遗憾的是,它不适用于更新任何类别,我只能创建新类别。

1 个答案:

答案 0 :(得分:1)

在您的存储库中,您可以创建更新功能并将实体状态设置为已修改。

public abstract class Repository<T>
{    
   public void Update(T entity) {
        Context.Entry(entity).State = EntityState.Modified;
   }
}