Asp.net mvc 使用Linq To SQL从MVC3视图模型更新记录

Asp.net mvc 使用Linq To SQL从MVC3视图模型更新记录,asp.net-mvc,linq-to-sql,viewmodel,Asp.net Mvc,Linq To Sql,Viewmodel,我正在尝试通过Linq to SQL使用ViewModel中的值更新数据库中的记录。我让它工作,但它已经停止(更多关于这个稍后) 我有一个映射到表的客户域对象。我不需要所有字段,所以我使用AutoMapper将其映射到一个ViewModel(CustomerEditVM),该ViewModel包含一个子集Customer字段。我在我的服务层中执行此操作: public CustomerEditVM GetCustomerEditVMById(int custId) { var domai

我正在尝试通过Linq to SQL使用ViewModel中的值更新数据库中的记录。我让它工作,但它已经停止(更多关于这个稍后)

我有一个映射到表的客户域对象。我不需要所有字段,所以我使用AutoMapper将其映射到一个ViewModel(CustomerEditVM),该ViewModel包含一个子集Customer字段。我在我的服务层中执行此操作:

public CustomerEditVM GetCustomerEditVMById(int custId)
{
    var domainCustomer = _repository.GetCustomerById(custId);

    Mapper.CreateMap<Customer, CustomerEditVM>();
    CustomerEditVM customer = Mapper.Map<Customer, CustomerEditVM>(domainCustomer);
    return customer;
}
更新以前工作正常,但现在失败,出现以下错误:

无法刷新指定的对象。对象不再存在 在数据库中

我不知道为什么以前它工作得这么好,现在不行,但很明显我没有使用Linq来正确更新数据库。我应该怎么做


谢谢

所以我的理解是Automapper并不是真的设计成这样的。它会像获取视图模型一样展平对象,但实际上不会以其他方式进行操作。我相信这是出于设计原因,因为Jimmy&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获取对象并更新它并调用SubmitChanges();在dataContext上。它会帮你解决的。我见过一些存储库接口包括一个更新方法,但它在Linq2Sql实现中没有任何作用。另外,在更新方法中调用SubmitChanges可能不是最好的主意,因为您可能希望更新may items,然后一次提交所有更改,这是SubmitChanges(即工作单元)的目的之一,所以我的理解是Automapper并不是真的设计成这样工作的。它会像获取视图模型一样展平对象,但实际上不会以其他方式进行操作。我相信这是出于设计原因,因为Jimmy&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获取对象并更新它并调用SubmitChanges();在dataContext上。它会帮你解决的。我见过一些存储库接口包括一个更新方法,但它在Linq2Sql实现中没有任何作用。另外,在更新方法中调用SubmitChanges可能不是最好的方法,因为您可能希望更新may项目,然后一次提交所有更改,这是SubmitChanges的目的(即工作单元)

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);
}
public void Update(Customer customer)
    {
        _dataContext.Customers.Attach(customer);
        _dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, customer);
        _dataContext.SubmitChanges();
    }