1

我是使用 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();
        }
    }
}

提前感谢您的任何建议!

4

1 回答 1

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

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

于 2012-11-14T21:50:33.777 回答