有没有更好的方式与实体框架更新我的实体?我的、实体、框架、方式

2023-09-03 00:42:17 作者:没你我会慌

我不是一个真正的问题,但我发现我开发这个code不是很好的方式。

I have not really a "problem" but I found the way I develop this code not really well.

我有我的国家控制器(编辑方式)(WebUI中层):

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();

    }

其实,你可以看到,我用Automapper地图我的国家实体(实体框架)和我的视图模型。 我用一个验证服务,使验证并更新我的对象(如果没有错误)到数据库中。事实是,我觉得我必须让我的对象从数据库中通过其ID来保存这个对象。我认为有可能是更好的解决方案来更新我的对象(因为我不希望映射为我的对象的所有领域,从DB每次获得国家)

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();

有没有更好的解决方案,以挽救我的对象与实体Framwork还是我没有选择?

Is there a better solution to save my objects with the entity Framwork or I have no choice ?

谢谢!

推荐答案

一般来说,你可以升级你的对象,而不从数据库加载它,但你必须知道这个ID。

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();    
} 

我没有用你的资料库,而是我用ObjectContext的实例。这code要求的国家例如设置了ID,姓名和ISO code。该更新将只在名称和ISO code场进行。

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.

但我不得不提一提,我不使用这种方式。装载实体首先是EF更好的方法,当你开始用复杂的实体和关系的工作。

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.