Я работаю над сайтом MVC с Entity Framework Code Сначала, используя Ninject для DI для контроллеров, и я столкнулся с вопросом дизайна. Я видел два метода, используемых для обновлений с помощью Code First. Первым использует "получить по идентификатору," изменяет значения объекта возвращаемые, а затем вызывает Context.SaveChanges()
, как это:Repository.Update стратегия с использованием EF4 Code First?
Контроллер:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
//Create a vm to hold the data from the form.
var sectionVm = new SectionEditViewModel();
//Copy the data from the http header to the object.
UpdateModel(sectionVm);
//Get the object from the database.
//_sectionRepository is injected in to the constructor.
var section = _sectionRepository.GetById(sectionVm.SectionId);
//Map from the view model to the actual model.
var viewSection = Mapper.Map(sectionVm, section);
_sectionRepository.Update();
return RedirectToAction("Index");
}
Repository:
public void Update()
{
_context.SaveChanges();
}
второй метод создает объект модели, привязывает его к контексту, изменяет состояние объекта, затем вызывает SaveChanges()
. Иллюстрированный здесь с методом испытаний как потребитель: Тест:
[TestMethod]
public void CanUpdateSection()
{
var repo = new SectionRepository();
var testSection = GetMockSection();
testSection.SomeProperty = "A new value";
testContact.AnotherProperty = "Another new value";
repo.Update(testSection);
var persistedUpdatedSection = repo.GetById(testSection.Id);
Assert.IsNotNull(persistedUpdatedSection);
CompareSections(testSection, persistedUpdatedSection);
}
Repository:
public void Update(Section entity)
{
using(var context = new SectionContext())
{
context.Sections.Attach(entity);
context.Entry(entity).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
}
Какой путь предпочтительнее, или есть другой, лучший способ?