I have not really a "problem" but I found the way I develop this code not really well.
I have my countries controller (Edit method) (WebUI layer):
[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);
}
And my validation Service (domain layer) :
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();
}
Actually, as you can see, I use Automapper to map my Country entity (Entity Framework) and my view Model.
I use a validation service that makes validation and update my object (if no errors) to the Database. The fact is that I feel that I must get my object from the DB by its Id to save this object. I think that there is maybe a better solution to update my object (because I don't want to map all fields for my objects and get the Country from DB each time)
var countryToUpdate = _groupsRepository.getCountryById(country.CountryId);
countryToUpdate.CountryId = country.CountryId;
countryToUpdate.Name = country.Name;
countryToUpdate.ISOCode = country.ISOCode;
_groupsRepository.SaveChanges();
Is there a better solution to save my objects with the entity Framwork or I have no choice ?
Thanks !
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…