我喜歡在我的倉庫保存方法與實體框架的輔助方法我從網上得到了一起。 SaveCustomer是我的存儲庫類方法,它下面是輔助類。在你的情況,你會通過你的模型到
brandRepository.SaveProdctBrand(productBrand)
(有助於闡明良好的命名規則和的FxCop規則的名稱)
public void SaveCustomer(Customer customer)
{
using (var ctx = new WebStoreEntities())
{
if (customer.CustomerId > 0)
{
//It's an existing record, update it.
ctx.Customers.AttachAsModified(customer);
ctx.SaveChanges();
}
else
{
//its a new record.
ctx.Customers.AddObject(customer);
ctx.SaveChanges();
}
}
}
的輔助類如下
public static class EntityFrameworkExtensions
{
/// <summary>
/// This class allows you to attach an entity.
/// For instance, a controller method Edit(Customer customer)
/// using ctx.AttachAsModified(customer);
/// ctx.SaveChanges();
/// allows you to easily reattach this item for udpating.
/// Credit goes to: http://geekswithblogs.net/michelotti/archive/2009/11/27/attaching-modified-entities-in-ef-4.aspx
/// </summary>
public static void AttachAsModified<T>(this ObjectSet<T> objectSet, T entity) where T : class
{
objectSet.Attach(entity);
objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
/// <summary>
/// This marks an item for deletion, but does not currently mark child objects (relationships).
/// For those cases you must query the object, include the relationships, and then delete.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objectSet"></param>
/// <param name="entity"></param>
public static void AttachAsDeleted<T>(this ObjectSet<T> objectSet, T entity) where T : class
{
objectSet.Attach(entity);
objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Deleted);
}
public static void AttachAllAsModified<T>(this ObjectSet<T> objectSet, IEnumerable<T> entities) where T : class
{
foreach (var item in entities)
{
objectSet.Attach(item);
objectSet.Context.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
}
}
}