Мне нравится иметь метод save в моем репозитории в сочетании с вспомогательным методом, который я получил из сети. 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);
}
}
}