用EntityDataSource替换SqlDataSource

时间:2014-10-29 08:57:03

标签: asp.net entity-framework

我有一个带有 countryID 列的DataGrid (目标),它被绑定到DropDownList以查看国家/地区。我也有国家/地区 countryGroups 表,其中 countries.countryGroupId = countryGroups.countryGroupId 。列表必须格式化,因此我使用SqlDataSource来获取格式化列表:

SELECT   c.countryID, cg.countryGroupName+': '+c.CountryName as Name
FROM     countries AS c INNER JOIN
         countries_groups AS cg ON c.countryGroupID = cg.countryGroupID
ORDER BY cg.Sort, c.CountryName

此处的下拉列表最初绑定到sqldatasource:

<asp:DropDownList ID="ddlCountryID" runat="server" Width="160px" DataSourceID="dsCountries"
     AppendDataBoundItems="true"  DataTextField="Name" DataValueField="countryID" 
     SelectedValue='<%# Bind("countryID") %>'>
     <asp:ListItem Value="" Text="Select"></asp:ListItem>
</asp:DropDownList>

我想将国家/地区字段的SqlDataSource替换为EntityDataSource。我创建了以下 ProductionModel

ProductionModel.edmx

VS2010已创建公共部分类 ProductionEntities:ObjectContext ...
我创建了一个EntityDataSource:

<asp:EntityDataSource ID="EntityDataSource1" runat="server" 
    ConnectionString="name=ProductionEntities" 
    DefaultContainerName="ProductionEntities" EntitySetName="countries" 
    Include="" 
    onquerycreated="EntityDataSource1_QueryCreated" 
    ContextTypeName="ASPWebApp.Datasource.ProductionEntities">

我的问题是,使用EntityDataSource进行绑定所需的其他步骤是什么?
提前谢谢!

更新 解决方案如下(感谢@Gaurav Jain)

protected void ddlCountryID_OnInit(object sender, EventArgs e) {
  DropDownList ddlCountryID = sender as DropDownList;
  ddlCountryID.DataSource = (from c in db.suppliers_countries
                             join cg in db.suppliers_countries_groups on c.countryGroupID equals cg.countryGroupID
                             orderby cg.Sort, c.CountryName
                             select new {
                                    c.countryID,
                                    Name = cg.countryGroupName + ": " + c.CountryName
                             });
}

和下拉列表成为:

<asp:DropDownList ID="ddlCountryID" runat="server" Width="160px" AppendDataBoundItems="true"  
                  SelectedValue='<%# Bind("countryID") %>' **OnInit="ddlCountryID_OnInit"**  
                  DataTextField="Name" DataValueField="countryID">
                  <asp:ListItem Value="" Text="Select"></asp:ListItem>
</asp:DropDownList>

1 个答案:

答案 0 :(得分:2)

您可以使用此查询。

       ProductionEntities db = new ProductionEntities();
       ddlCountryID.DataSource = (from c in db.countries 
                                  join cg in db.countries_groups on c.countryGroupID       
                                  equals cg.countryGroupID 
                                  select new 
                                  { c.countryID,   
                                    Name = cg.countryGroupName + " " + c.CountryName,cg.Sort})
                                   .OrderBy(w => new {w.countryID,w.sort });      
        ddlCountryID.DataTextField = "Name";
        ddlCountryID.DataValueField = "countryID";
        ddlCountryID.DataBind();