GridView with ObjectDatasource UpdateMethod

半腔热情 提交于 2019-12-05 22:20:53

You can also solve this by setting ConflictDetection="CompareAllValues" in the ObjectDataSource:

<asp:ObjectDataSource ID="objDsEmployees"
    runat="server"
    DeleteMethod="Delete"
    InsertMethod="Insert"
    SelectMethod="GetAll"
    UpdateMethod="Update"
    DataObjectTypeName="App.Core.Domain.Employee"
    TypeName="App.Core.Services.EmployeeService"
    OldValuesParameterFormatString="original{0}"
    ConflictDetection="CompareAllValues" />

Then in the Update method in EmployeeService we fetch the original employee first by its id, then we merge this original employee with the updated employee. This makes sure that not updated properties don't become null - although it requires an extra call to the database:

public void Update(Employee originalEmployee, Employee employee)
{
    // Get the original employee by its id.
    Employee fullOriginalEmployee = GetById(originalEmployee.EmployeeId);

    // Merge the data of the updated employee with the original employee.
    fullOriginalEmployee.Name = employee.Name;
    fullOriginalEmployee.Email = employee.Email;
    fullOriginalEmployee.Telephone = employee.Telephone;
    fullOriginalEmployee.BirthDate = employee.BirthDate;

    // Persist changes in database.
    SaveChanges();
}

I solved this by changing the ObjectDataSource to:

<asp:ObjectDataSource 
    ID="objDsEmployees"
    runat="server"
    DeleteMethod="Delete"
    InsertMethod="Insert"
    SelectMethod="GetAll"
    TypeName="MySite.Services.EmployeeService"
    UpdateMethod="Update">
    <UpdateParameters>
        <asp:Parameter Name="employeeId" Type="Int32" />
        <asp:Parameter Name="name" Type="String" />
        <asp:Parameter Name="email" Type="String" />
    </UpdateParameters>
</asp:ObjectDataSource>

And the Update method in the service layer to:

public void Update(int employeeId, string name, string email)
{
    var employee = GetById(employeeId);
    employee.Name = name;
    employee.Email = email;

    _db.SaveChanges();
}

Other solutions are, however, more than welcome!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!