Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

.net - 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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...