【发布时间】:2011-01-05 00:17:06
【问题描述】:
我没有真正的“问题”,但我发现我开发这段代码的方式不是很好。
我有我的国家控制器(编辑方法)(WebUI 层):
[HttpGet]
public ActionResult Edit(int id)
{
var country = _groupsRepository.getCountryById(id);
Mapper.CreateMap<Country, CountriesEditViewModel>();
CountriesEditViewModel viewModel = Mapper.Map<Country, CountriesEditViewModel>(country);
return View(viewModel);
}
//
// POST: /CountriesAdmin/Edit/5
[HttpPost]
public ActionResult Edit(int id, CountriesEditViewModel viewModel)
{
try
{
if (ModelState.IsValid)
{
Mapper.CreateMap<CountriesEditViewModel, Country>();
Country country = Mapper.Map<CountriesEditViewModel, Country>(viewModel);
country.Name = IntranetTools.UppercaseFirst(country.Name.Trim());
country.ISOCode = country.ISOCode.ToLower();
_countryValidationService.UpdateCountry(country);
}
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Index");
else return View(viewModel);
}
还有我的验证服务(域层):
public void UpdateCountry(Country country)
{
EnsureValidForUpdate(country);
// UPDATE
var countryToUpdate = _groupsRepository.getCountryById(country.CountryId);
countryToUpdate.CountryId = country.CountryId;
countryToUpdate.Name = country.Name;
countryToUpdate.ISOCode = country.ISOCode;
_groupsRepository.SaveChanges();
}
实际上,如您所见,我使用 Automapper 来映射我的 Country 实体(实体框架)和我的视图模型。 我使用验证服务进行验证并将我的对象(如果没有错误)更新到数据库。事实是我觉得我必须通过它的 ID 从数据库中获取我的对象来保存这个对象。我认为更新我的对象可能有更好的解决方案(因为我不想为我的对象映射所有字段并每次都从数据库中获取国家)
var countryToUpdate = _groupsRepository.getCountryById(country.CountryId);
countryToUpdate.CountryId = country.CountryId;
countryToUpdate.Name = country.Name;
countryToUpdate.ISOCode = country.ISOCode;
_groupsRepository.SaveChanges();
是否有更好的解决方案来使用实体框架保存我的对象,或者我别无选择?
谢谢!
【问题讨论】:
标签: .net entity-framework asp.net-mvc-2 entity