开发者

Is there a better way to update my entities with the Entity framework?

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 !


Generally you can update your object without loading it from DB but you have to know its Id.

Your update function can look like:

public void UpdateCountry(Country country)     
{         
  EnsureValidForUpdate(country); 
  _objectContext.Attach(country);

  ObjectStateEntry entry = _objectContext.ObjectStateManager.GetObjectStateEntry(country);
  entry.SetModifiedProperty("Name");
  entry.SetModifiedProperty("ISOCode");

  _objectContext.SaveChanges();    
} 

I didn't use your repository and instead I used ObjectContext instance. This code requires that your Country instance has set Id, Name and ISOCode. The update will be done only on Name and ISOCode fields.

But I have to mention that I'm not using this way. Loading entity first is much better approach in EF when you start to work with complex entities and relations.


You can call this method in a loop. Then after the loop call context.SaveChanges();

    public void UpdateCountry(Item updateItem)     
    {         
        context.YourDbObjects.Attach(updateItem);

        DbEntityEntry<Item> entry = context.Entry(updateItem);

        entry.State = EntityState.Modified;
    } 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜