C# 如何使用ObjectDataSource将复杂实体类型绑定到Gridview

C# 如何使用ObjectDataSource将复杂实体类型绑定到Gridview,c#,asp.net,C#,Asp.net,我有一个实体 class Person { public int Age{get;set;} public string Name{get;set;} public Department Dept{get;set;} } class Department { public int DeptId{get;set;} public string DeptName{get;set} } 现在,我使用ObjectDataSource控件将集合绑定到GridView。 在TemplateField下,

我有一个实体

class Person
{
public int Age{get;set;}
public string Name{get;set;}
public Department Dept{get;set;}
}

class Department
{
public int DeptId{get;set;}
public string DeptName{get;set}
}
现在,我使用ObjectDataSource控件将集合绑定到GridView。 在TemplateField下,Dept of Person类如下所示

<EditItemTemplate>
      <asp:DropDownList ID="cmbStatus" DataTextField="DeptName" SelectedValue='<%# Bind("Dept.DeptId") %>'
          DataValueField="DeptId" runat="server" CssClass="ddl150px ddlbg" 
          DataSourceID="deptCollection" />
      <asp:ObjectDataSource ID="deptCollection" runat="server" 
                   SelectMethod="GetDeptList" TypeName="LIMS.BusinessObject.Department" >
     </asp:ObjectDataSource>
 </EditItemTemplate>

现在,我的网格使用

            <asp:ObjectDataSource ID="PersonCollection" runat="server" 
                SelectMethod="GetPersonList" 
                TypeName="LIMS.BusinessObject.Person" 
                DataObjectTypeName="LIMS.DomainModel.Person" 
                DeleteMethod="Delete" InsertMethod="Create" UpdateMethod="Update" 
                ondeleting="PersonCollection_Deleting" 
                onupdating="PersonCollection_Updating">  
            </asp:ObjectDataSource>


现在,当我尝试更新这个Person实体时,它会抛出错误,因为下拉列表显示值字段和文本字段,Person实体需要一个Dept实体,它实际上绑定到dropdownlist

您不应该在表示层aspx中直接使用复杂的实体。因为如果您更改域模型,例如添加一些字段,您将更新应用程序的每个aspx。您应该提供如下“视图模型”:

class PersonView
{
  public int Age{get;set;}
  public string Name{get;set;}

  public int DeptId{get;set;}
  public string DeptName {get { ... }}
}
它不应该是DTO:您不需要在主机之间传输要序列化的数据,而是视图的模型

薄层可以将模型实体转换为视图模型。ObjectDataSource可以很好地支持它