使用EF 5.0查找表

时间:2012-11-14 21:34:39

标签: c# entity-framework

我是EF的新手,但我无法抗拒这个概念,现在我被卡住了。我正在开发一个网页表格来取代纸质调查。数据结构具有大量查找表。我已经构建了基于EF的数据访问层(DAL)。我想创建一个用户控件,可以传递与查找表关联的实体,然后简单地将该实体绑定到下拉列表,但是,我正在努力完成此任务所需的反射。

我的代码如下:

    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

namespace ABC.ABC.Controls
{
    public partial class ABCQuestionSingle : System.Web.UI.UserControl
    {
        CareDAL.ABC.Entities DAL = new CareDAL.ABC.Entities();

        private string dataTextField;
        public string DataTextField
        {
            get { return dataTextField; }
            set { dataTextField = value; }
        }

        private string dataValueField;
        public string DataValueField
        {
            get { return dataValueField; }
            set { dataValueField = value; }
        }

        private string entityName;
        public string EntityName
        {
            get { return entityName; }
            set { entityName = value; }
        }

        //I've tried this unsuccessfully!
        public List<TEntity> GetList<TEntity>(string _name)
        {
            IEnumerable<TEntity> enumerable = (IEnumerable<TEntity>)(typeof(CareDAL.NDNQI.DST_ABCEntities).GetProperty(_name).GetValue(DAL, null));
            return enumerable.ToList();
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            ddlResponse.DataTextField = "PrimaryReason";
            ddlResponse.DataValueField = "ReasonId";
            ddlResponse.DataSource = DAL.PrimaryReasons.ToList();
            ddlResponse.DataSource = GetList(entityName); //Obvious error, but not sure how to handle this!
            ddlResponse.DataBind();
        }
    }
}

提前感谢您的任何建议!

1 个答案:

答案 0 :(得分:1)

public partial class ABCQuestionSingle : System.Web.UI.UserControl
{
    public void LoadDropDown<T>(string valueProperty, string textProperty)
        where T : class
    {
        ddlResponse.DataTextField = textProperty;
        ddlResponse.DataValueField = valueProperty;
        ddlResponse.DataSource = new CareDAL.ABC.Entities().Set<T>();
        ddlResponse.DataBind();
    }
}

然后,您可以从调用页面的加载事件(或任何其他事件)中调用此方法