有没有更好的方法来使用实体框架更新我的实体?

发布于 2024-10-10 12:37:47 字数 2212 浏览 1 评论 0原文

我并没有真正的“问题”,但我发现我开发这段代码的方式不太好。

我有我的国家控制器(编辑方法)(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 来映射我的国家/地区实体(实体框架)和我的视图模型。 我使用验证服务来验证并将我的对象(如果没有错误)更新到数据库。事实上,我觉得我必须通过 ID 从数据库中获取对象来保存该对象。我认为可能有更好的解决方案来更新我的对象(因为我不想映射我的对象的所有字段并每次从数据库获取国家/地区)

        var countryToUpdate = _groupsRepository.getCountryById(country.CountryId);
        countryToUpdate.CountryId = country.CountryId;
        countryToUpdate.Name = country.Name;
        countryToUpdate.ISOCode = country.ISOCode;
        _groupsRepository.SaveChanges();

是否有更好的解决方案来使用实体框架保存我的对象或我别无选择?

谢谢 !

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 !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一袭白衣梦中忆 2024-10-17 12:37:47

一般来说,您可以更新对象而无需从数据库加载它,但您必须知道它的 ID。

您的更新函数可能如下所示:

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 实例。此代码要求您的 Country 实例已设置 Id、Name 和 ISOCode。更新将仅在名称和 ISOCode 字段上完成。

但我必须指出,我没有使用这种方式。当您开始处理复杂的实体和关系时,在 EF 中首先加载实体是更好的方法。

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.

陌若浮生 2024-10-17 12:37:47

您可以在循环中调用此方法。然后在循环之后调用 context.SaveChanges();

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

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

        entry.State = EntityState.Modified;
    } 

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;
    } 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文