2

Hi all I have a code like this inside entityframework (I want to change many items at the same time I dont know whether we can use a loop like this but it throws an exception like this:

LINQ to Entities does not recognize the method 'Int32 get_Item(Int32)' method, and this method cannot be translated into a store expression.

Code:

        try
        {
            for (int j = 0; j < ids.Count; j++)
            {
                using (OzgorenEntities2 context = new OzgorenEntities2())
                {
                        Stock st = context.Stocks.First(i => i.id == ids[j]);
                        st.stockAmount =  amounts[j];
                        context.SaveChanges();
                }
            }
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }

to be honest I searched and only find that converting is not working in server side but I dont convert it there what might be solution for me ?

Thanks

1
  • 3
    LINQ to Entities is getting tripped up by your using ids[j] as a value in your query. It's totally obvious to you and me that you just want to use a value within the array, but as far as the query provider is concerned, you're trying to access the indexer property called get_Item on the array, and it doesn't know how to generate SQL code for that. Commented May 8, 2013 at 15:41

2 Answers 2

5

try to introduce a variable for the ids value at the given index

            using (OzgorenEntities2 context = new OzgorenEntities2())
            {
                    var id = ids[j];
                    Stock st = context.Stocks.First(i => i.id == id);
                    st.stockAmount =  amounts[j];
                    context.SaveChanges();
            }
Sign up to request clarification or add additional context in comments.

Comments

2

You should add intermediate variable to storage value ids[j]:

    try
    {
        for (int j = 0; j < ids.Count; j++)
        {
            var tempId = ids[j];
            using (OzgorenEntities2 context = new OzgorenEntities2())
            {
                    Stock st = context.Stocks.First(i => i.id == tempId);
                    st.stockAmount =  amounts[j];
                    context.SaveChanges();
            }
        }
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }

It is due to nature of IQueriable expressions. LINQ to Entities don't know how to transfer expression i => i.id == ids[j] to SQL statement.

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.