gpt4 book ai didi

c# - 在 MVC 5 中使用 Entity Framework 6 更新相关数据

转载 作者:行者123 更新时间:2023-11-30 18:24:10 24 4
gpt4 key购买 nike

使用 EntityFramework 6,我想在以下情况下更新 Customer:

public class Customer
{
public int Id {get; set;}
// 100 more scalar properties
public virtual IList<Consultant> Consultants {get;set;}
}

public class Consultant
{
public int Id {get; set;}
public virtual IList<Customer> Customers{get;set;}
}

这是我的编辑 View 的 ViewModel:

public class CustomerViewModel
{
public string[] SelectedConsultants { get; set; }
public IEnumerable<Consultants> AllConsultants{ get; set; }
public Customer Customer{ get; set; }
}

这是我的 Edit-ActionMethod:

    [HttpPost]
public ActionResult Edit(CustomerViewModel vm)
{
if (ModelState.IsValid)
{
// update the scalar properties on the customer
var updatedCustomer = vm.Customer;
_db.Customers.Attach(updatedCustomer );
_db.Entry(updatedCustomer ).State = EntityState.Modified;
_db.SaveChanges();

// update the navigational property [Consultants] on the customer
var customer = _db.Customers
.Include(i => i.Customers)
.Single(i => i.Id == vm.Customer.Id);

Customer.Consultants.Clear();
_db.Consultants.Where(x => vm.SelectedConsultants
.Contains(x.Id)).ToList()
.ForEach(x => customer.Consultants.Add(x));

_db.Entry(customer).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(vm);
}

这有效,标量属性和顾问都可以从编辑 View 中更新。但是,我在我的 Controller 中执行了两个 _db.SaveChanges();。有没有更简单的方法来更新 Customer?因为 Customer 有很多属性,我最好不要对 Customervm.Customer 上的所有参数进行手动匹配。

我找到了以下资源:

  1. asp.net official似乎过于复杂(参见添加部分教师编辑页面的类(class)分配)加上需要我明确写下客户的所有参数)
  2. this popular thread所以。方法 3 看起来像我需要的,但我无法更新导航属性。

最佳答案

我认为没有必要调用 SaveChanges 两次。

你有没有试过这样的事情:

      var customer = _db.Customers
.Where(c => c.Id== vm.Customer.Id)
.Include(c => c.Consultants)
.SingleOrDefault();

customer.Consultants = _db.Consultants
.Where(x => vm.SelectedConsultants.Contains(x.Id)).ToList();

_db.SaveChanges();

编辑:

好的,不确定这是否可行,但您可以尝试使用 Automapper:

            var customer = Mapper.Map<Customer>(vm.Customer);
_db.Entry(customer).State = EntityState.Modified;

customer.Consultants = _db.Consultants.Where(x => vm.SelectedConsultants.Contains(x.Id)).ToList();

_db.SaveChanges();

关于c# - 在 MVC 5 中使用 Entity Framework 6 更新相关数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31589748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com