Databinding ASP.net DropDownList with Entity Framework

3-tier asp.net data-binding entity-framework

Question

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

Accepted Answer

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;

Popular Answer

Why don't you just use a List<>?

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


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why