Using Contains in the "select" phase of LINQ to Entity causes an unexpected error.

c# entity-framework linq-to-entities


I'm currently using a LINQ query to search across an Entity Framework entity. Here is a short description of the issue:

//a list of my allies
List<int> allianceMembers = new List<int>() { 1,5,10 };

//query for fleets in my area, including any allies (and mark them as such)
var fleets = from af in FleetSource
             select new Fleet 
                 fleetID = af.fleetID,
                 fleetName = af.fleetName,
                 isAllied = (allianceMembers.Contains(af.userID) ? true : false)

In essence, what I'm doing is collecting a collection of fleets. All of the people who are associated with me are listed as INTs in the allianceMembers list. If the owner of the fleet is on that list, I want to set isAllied = true; otherwise, I want it to be false.

When I perform this, I get the error "LINQ to Entities does not recognize the method 'Boolean Contains(Int32)' method," which I can see when I do this.

If I had used includes in the where clause of the query, I could understand receiving this issue, but why would I receive it in the select? By this point I would assume the query would have executed and returned the results. This little piece of code does nothing to limit my data in any way.

Any advice on other ways I may put up the isAllied flag and achieve my goals?


4/29/2009 12:37:11 PM

Accepted Answer

var fleets = from af in FleetSource;

var x = from u in fleets.ToList()
                         select new Fleet
                            fleetID = u.fleetID,
                            fleetName = u.fleetName,
                            isAllied = (allianceMembers.Contains(u.userID) ? true : false)

calling ToList() the query is run on fleets, and you may utilize it afterwardsContains() .

4/27/2010 1:59:03 PM

Popular Answer

This was lifted from an earlier response.

Does not support contains.

The operators IN and JOIN are not the same (Filtering by IN never changes the cardinality of the query).

Use the join technique in place of performing it that way. It's somewhat difficult to understand without using the query operators, but once you get it, you've got it.

var foo = 
model.entitySet.Join(  //Start the join
values, //Join to the list of strings
e => e.Name, // on entity.Name
value => value, //equal to the string
(ModelItem ent, String str) => ent);//select the entity

Here, the query operators are being used.

var foo = from e in model.entitySet
join val in values on
e.Name equals val
select e;

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow