2

I've got numerous LINQ queries inside of for loops that look like this:

Department department = db.Departments.Single(d => d.DepartmentID == teams[i].DepartmentID);

The problem is LINQ doesn't like to compare against an array element and throws the exception LINQ to Entities does not recognize the method 'get_Item(Int32)'. Is there a nicer way to get around this besides declaring local variables for each of the properties in the teams list I want to select against? I'd like to avoid filling my for loops up with things like

int departmentID = teams[i].DepartmentID;
string teamName = teams[i].TeamName;

etc.

3 Answers 3

8

I'd like to avoid filling my for loops up with things like...

Unfortunately, that is typically the best option. The expression evaluation needs to be able to convert the expression tree into SQL, and it doesn't know how to handle array elements. Making temporary variables is the simplest, most maintainable way to handle this scenario.

Sign up to request clarification or add additional context in comments.

Comments

5

I don't know that this will fix your problem but you could try changing your for loop to a for each loop so that you have a reference to the current object rather than accessing it by index. The problem is that SQL Server has no notion of what an array is so when you try to use that valid C# syntax, it doesn't know how to translate it into an expression tree to produce the necessary SQL. If the for each suggestion doesn't work then I think you're stuck doing it how you are now.

2 Comments

Normally I would. However in this case I'm indexing 13 different arrays in the for loop.
@Legion that's unfortunate. I don't think there are any options better than assigning to local variables.
0

Why wouldn't you write something like that:

var query = from d in db.Departments
                from t in teams
                where d.DepartmentID == t.DepartmentID && d.Team == t.TeamName
                select d;

This can be easily converted to Expression tree and finally to SQL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.