views:

100

answers:

1

I'm using LINQ to Entities in the Data layer of my application, but am getting hammered by a NotSupportedException in a call to results.ToList(). Here is the function causing the exception:

    public List<Organization> GetByLocation(Location l)
    {
        using (Entities entities = new Entities())
        {
            var results = from o in entities.OrganizationSet
                          where o.Location == l
                          select o;

            return results.ToList<Organization>();
        }
    }

The point is to return a list of all the Organizations at a given Location to the Service Layer (which returns it to the MVC Controller, which converts it to JSON then returns it to the client). The Service Layer is expecting a List to be returned.

This may be pretty simple... any help?

+6  A: 
public List<Organization> GetByLocation(Location l)
{
    using (Entities entities = new Entities())
    {
        var results = from o in entities.OrganizationSet
                      where o.Location.Id == l.Id
                      select o;

        return results.ToList<Organization>();
    }
}

Since this query will be converted to SQL, you can't do a reference comparison of l. Compare by the PK, instead.

Craig Stuntz
Sheesh, I do this millions of times in Java in Hibernate Queries and totally forget when working in c#. (And if anyone asks, I'm avoiding NHibernate for the moment to try to keep this app SOMEWHAT lightweight while still somewhat well designed).
Jason
By the way - are there any good reasons not to automatically turn a reference comparison into a primary key comparison? This would shorten queries especially in the case of composite keys.
Daniel Brückner
Daniel, it seems like it should be possible, but I haven't thought through the consequences. For starters, `==` can be overloaded.
Craig Stuntz