C# 使用MVC5中的实体框架6更新相关数据
使用EntityFramework 6,我想在以下场景中更新Customer:C# 使用MVC5中的实体框架6更新相关数据,c#,asp.net,asp.net-mvc,entity-framework,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Entity Framework,Asp.net Mvc 4,使用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 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;}
}
这是可行的,标量属性和顾问都可以从编辑视图中更新。但是,我正在做两个\u db.SaveChanges()代码>在我的控制器中。是否有一种更新客户的不太复杂的方法?因为Customer
有很多属性,我最好不要手动匹配Customer
和vm.Customer
上的所有参数
我找到了以下资源:
似乎过于复杂(参见添加部分
将课程作业添加到讲师编辑页面)以及
me明确写入客户的所有参数)
就这样。方法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();
var customer=Mapper.Map(vm.customer);
_db.Entry(customer.State=EntityState.Modified;
customer.Consultants=_db.Consultants.Where(x=>vm.SelectedConsultants.Contains(x.Id)).ToList();
_db.SaveChanges();
Hi Alan,您的建议没有考虑到客户的标量属性(客户名称等)可能也已更改。此外,我认为实体框架希望使用.Add或.Remove在ICollection中添加和删除。编辑:好的,我刚刚检查过,它确实拯救了顾问;o) 您可以尝试使用Automapper将属性从vm映射到模型。
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();
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();