Search code examples
asp.netentity-frameworkdata-binding3-tier

Databinding ASP.net DropDownList with Entity Framework


I'm trying to bind an ASP.net DropDownList to the results of an entity framework query, while still maintaining multi-tier separation. (i.e. I don't want my UI code to contain query details, nor my Data Layer code to have UI dependencies.) My code-behind in the Page_Load event handler looks like this:

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

While my data code looks like this (there's an intermediate business layer as well, but there no processing there as yet -- just a pass-through.):

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

When I get to the DocTypeDropDownList.DataBind();, it throws an ObjectDisposedException with the message "DocTypeDropDownList.DataBind();". Can anyone advise me on the best way to tackle this?

Thanks, Andy


Solution

  • Don't you have to detach the objects from the context? 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;