使用实体框架将ASP.net DropDownList数据绑定

时间:2009-01-02 17:09:30

标签: asp.net entity-framework data-binding 3-tier

我正在尝试将ASP.net DropDownList绑定到实体框架查询的结果,同时仍然保持多层分离。 (即我不希望我的UI代码包含查询详细信息,也不希望我的数据层代码具有UI依赖性。)我在Page_Load事件处理程序中的代码隐藏如下所示:

        IEnumerable<Lookup> TypesLookup = Business.DocumentBO.GetDocumentTypes(_LookupTypeID);
        DocTypeDropDownList.DataSource = TypesLookup;
        DocTypeDropDownList.DataTextField = "Description";
        DocTypeDropDownList.DataValueField = "LookupID";
        DocTypeDropDownList.DataBind();

虽然我的数据代码看起来像这样(也有一个中间业务层,但目前还没有处理 - 只是传递。):

    public static IEnumerable<Lookup> GetLookups(int LookupTypeID)
    {
        using (VLFDocumentEntities context = new VLFDocumentEntities())
        {
            IEnumerable<Lookup> l = (from c in context.Lookup
                        where c.LookupTypeID == LookupTypeID
                        select c);

            return l;
        }
    }

当我到达DocTypeDropDownList.DataBind();时,它会抛出一个带有消息“DocTypeDropDownList.DataBind();”的ObjectDisposedException。任何人都可以告诉我解决这个问题的最佳方法吗?

谢谢,   安迪

2 个答案:

答案 0 :(得分:2)

您是否必须从上下文中分离对象? E.g:

IEnumerable<Lookup> l = (from c in context.Lookup
                        where c.LookupTypeID == LookupTypeID
                        select c);
foreach (Lookup lookup in l)
  context.Detach(lookup);
return l;

答案 1 :(得分:1)

为什么不使用List&lt;&gt;?

public static List<Lookup> GetLookups(int LookupTypeID)
{
    using (VLFDocumentEntities context = new VLFDocumentEntities())
    {
        return (from c in context.Lookup
                    where c.LookupTypeID == LookupTypeID
                    select c).ToList();
    }
}
相关问题