使用Entity Framework 4填充DropDownList

时间:2011-01-17 10:31:29

标签: c# asp.net entity-framework

我需要一个非常简单的代码示例来使用Entity Framework 4填充DropDownList。

目前我使用此代码:

        using (TestHierarchyEntities context = new TestHierarchyEntities())
        {
            uxSelectNodeDestinationDisplayer.DataSource = context.CmsCategories.ToList();
            uxSelectNodeDestinationDisplayer.DataBind();
        }

但它不能正常工作......任何想法?感谢

3 个答案:

答案 0 :(得分:7)

这样的事情应该有效:

using (TestHierarchyEntities context = new TestHierarchyEntities())
        {
                var category = (from c in context.context
                                select new { c.ID, c.Desc }).ToList();

                DropDownList1.DataValueField = "MID";
                DropDownList1.DataTextField = "MDesc";
                DropDownList1.DataSource = category;
                DropDownList1.DataBind();                
         }

答案 1 :(得分:0)

using (dbEntities db = new dbEntities())
{
    ddlNewEmployee.DataSource = (from emp in db.CC_EMPLOYEE
                                    select new { emp.EmployeeID, emp.EmployeeCode }).ToList();

    ddlNewEmployee.DataTextField = "EmployeeCode";
    ddlNewEmployee.DataValueField = "EmployeeID";
    ddlNewEmployee.DataBind();
}

答案 2 :(得分:0)

这非常有效:

private COFFEESHOPEntities1 CoffeeContext = new COFFEESHOPEntities1();
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //getData();
        cbxCategory.DataSource = CoffeeContext.tblProductTypes.ToList();
        cbxCategory.DataTextField = "Description";
        cbxCategory.DataValueField = "ProductType";
        cbxCategory.DataBind();
    }
}