[英]Updating related Data with Entity Framework 6 in MVC 5
Using EntityFramework 6, I would like to update Customer in the following scenario: 使用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;}
}
This is my ViewModel for the edit view: 这是编辑视图的ViewModel:
public class CustomerViewModel
{
public string[] SelectedConsultants { get; set; }
public IEnumerable<Consultants> AllConsultants{ get; set; }
public Customer Customer{ get; set; }
}
This is my Edit-ActionMethod: 这是我的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);
}
This works and both scalar properties and consultants are updateable from the edit view. 这有效,标量属性和顾问都可以从编辑视图中更新。 However, I am doing two _db.SaveChanges();
但是,我正在做两个_db.SaveChanges();
in my controller. 在我的控制器中。 Is there a less complex way to update Customer
? 是否有一种不太复杂的方式来更新Customer
? Because Customer
has many properties, I'd preferably not do a manual matching of all parameters on Customer
and vm.Customer
. 因为Customer
有很多属性,所以我最好不要对Customer
和vm.Customer
上的所有参数进行手动匹配。
I have found the following resources: 我找到了以下资源:
I don't think it's necessary to call the SaveChanges twice. 我不认为有必要两次调用SaveChanges。
Have you tried something like this: 你尝试过这样的事情:
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();
Edit: 编辑:
Ok, not sure if this will work, but you can try using Automapper: 好的,不确定这是否有效,但您可以尝试使用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.