我正在尝试通过Linq To SQL使用ViewModel中的值更新数据库中的记录。我有它工作但它已经停止了(稍后会更多)。
我有一个映射到表的Customers域对象。我不需要所有字段,因此我使用AutoMapper将其映射到具有Customer字段子集的ViewModel(CustomerEditVM)。我在服务层执行此操作:
public CustomerEditVM GetCustomerEditVMById(int custId)
{
var domainCustomer = _repository.GetCustomerById(custId);
Mapper.CreateMap<Customer, CustomerEditVM>();
CustomerEditVM customer = Mapper.Map<Customer, CustomerEditVM>(domainCustomer);
return customer;
}
我将CustomerEditVM ViewModel发送到我的视图,用户编辑记录。在我的服务层中,我将其映射回Customer对象并在我的存储库中调用Update方法:
public void SaveCustomer(CustomerEditVM customer)
{
Mapper.CreateMap<CustomerEditVM, Customer>();
Customer newCust = Mapper.Map<CustomerEditVM, Customer>(customer);
_repository.Update(newCust);
}
这是我的存储库和Update方法:
namespace AuctionAdmin.Models.Repositories
{
public interface ICustomerRepository
{
Customer GetCustomerById(int custId);
void Update(Customer customer);
}
public class CustomerRepository : ICustomerRepository
{
private AuctionAdminDataContext _dataContext;
public CustomerRepository()
{
_dataContext = new AuctionAdminDataContext();
}
public Customer GetCustomerById(int custId)
{
var customer = _dataContext.Customers.SingleOrDefault(c => c.CustomerID == custId);
return customer;
}
public void Update(Customer customer)
{
_dataContext.Customers.Attach(customer);
_dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, customer);
_dataContext.SubmitChanges();
}
}
}
更新过去工作正常,但现在因此错误而失败:
无法刷新指定的对象。该对象不再存在 在数据库中。
我不确定为什么之前这么好用,现在我不知道我没有使用Linq来正确更新数据库。我该怎么做?
由于
答案 0 :(得分:1)
所以我的理解是,Automapper并不是真正意图以这种方式工作。它像你正在做的那样使你的视图模型变平,但它并没有真正做其他事情。我相信这是设计因为Jimmy&amp; Crew正在使用更多带有消息传递的命令模式来将内容保存回数据库。
但是,我知道这并不能解决你的问题。所以这里有一些事情。
使用Linq2Sql您需要拉出对象,然后更新它,然后保存它。这是 因为linq2sql正在跟踪对象的变化。但是,在请求之间,您不再拥有linq2sql对象。
public void SaveCustomer(CustomerEditVM customer)
{
//Get the customer from repo
var domainCustomer = _repository.GetCustomerById(customer.Id);
Mapper.CreateMap<CustomerEditVM, Customer>();
Customer newCust = Mapper.Map<CustomerEditVM, Customer>(domainCustomer);
_repository.Update(newCust);
}
然而,由于linq2sql和automapper的工作方式,这很可能不会起作用。即使映射确实有效,linq2sql也可能不会显示已对对象进行了更改。你最好手动绘制它。
此外,在Linq2Sql中确实没有更新。
public void Update(Customer customer)
{
_dataContext.Customers.Attach(customer);
_dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, customer);
_dataContext.SubmitChanges();
}
您需要做的就是从linq2sql获取对象更新它并调用SubmitChanges();在_dataContext上。它会照顾你。我看到一些存储库接口包含一个Update方法,但它在Linq2Sql实现中没有做任何事情。此外,在更新方法中调用SubmitChanges可能不是最好的想法,因为您可能想要更新,然后项目可以立即提交所有更改,这是submitchanges(即工作单元)的目的