gpt4 book ai didi

c# - 带有 ObjectDatasource UpdateMethod 的 GridView

转载 作者:行者123 更新时间:2023-11-30 16:17:27 25 4
gpt4 key购买 nike

我有一个包含 ASPxGridViewObjectDataSource 的 ASP.NET WebForms 页面:

<dx:ASPxGridView ID="gvEmployees" runat="server"
AutoGenerateColumns="False" DataSourceID="objDsEmployees"
KeyFieldName="EmployeeId">
<Columns>
<dx:GridViewCommandColumn VisibleIndex="0">
<EditButton Visible="True" />
</dx:GridViewCommandColumn>
<dx:GridViewDataTextColumn FieldName="EmployeeId" VisibleIndex="1" />
<dx:GridViewDataTextColumn FieldName="Name" VisibleIndex="2" />
<dx:GridViewDataTextColumn FieldName="Email" VisibleIndex="3" />
<dx:GridViewDataTextColumn FieldName="Telephone" VisibleIndex="5" />
</Columns>
</dx:ASPxGridView>
<asp:ObjectDataSource ID="objDsEmployees"
runat="server"
ConflictDetection="CompareAllValues"
DataObjectTypeName="MySite.Data.Models.Employee"
DeleteMethod="Delete"
OldValuesParameterFormatString="original{0}"
InsertMethod="Insert"
SelectMethod="GetAll"
TypeName="MySite.Services.EmployeeService"
UpdateMethod="Update" />

Employee 模型包含以下属性:

public class Employee
{
public int EmployeeId { get; set; }

public string Name { get; set; }

public string Email { get;

public string Password { get; set; }

public string Telephone { get; set; }
}

ObjectDataSource调用服务层的Update方法:

public void Update(Employee employee, Employee originalEmployee)
{
_db.Employees.Attach(originalEmployee);
_db.Entry(originalEmployee).CurrentValues.SetValues(employee);
_db.SaveChanges();
}

调用Update 方法时,参数employeeoriginalEmployee 仅包含在ASPxGridView< 中用作列的属性 和其他属性(例如 Password)为空。

有什么方法可以将这些值保存在某处吗?顺便说一句,我使用 Entity Framework 进行数据访问,使用 DevExpress 进行 GridView。

最佳答案

您还可以通过在 ObjectDataSource 中设置 ConflictDetection="CompareAllValues" 来解决此问题:

<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" />

然后在 EmployeeServiceUpdate 方法中,我们首先通过其 id 获取原始员工,然后我们将这个原始员工与更新后的员工合并。这确保未更新的属性不会变为 null - 尽管它需要额外调用数据库:

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();
}

关于c# - 带有 ObjectDatasource UpdateMethod 的 GridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17156991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com