Jason
Jason

Reputation:

Iterating over LINQ entity results

I have what I thought was a very simple piece of code, but the results are baffling me. I'm querying entities using LINQ, and then iterating over the results to create an array. I'm watching the traffic to and from the database, and everything looks good there. When I copy the query that LINQ is sending to SQL and run it directly against SQL I get the expected results. However, when I iterate over the results--or even put a watch on the results--every record is exactly the same. This is NOT what SQL is returning. What am I doing wrong?

var eventList = from e in entityContext.AuctionSet select e;

ArrayList DayArray = new ArrayList();
int i = 0;

foreach (Auction ae in eventList)
{
    // If I put a watch on eventList all the records are the same!
    Auction temp = ae; // Even tried copying to a temp value per another solution

    // Even though the records are different in the database, 
    // and the correct number of records are returned, EVERY "ae" instance 
    // has the exact same values!
    DayArray.Add(new {
                id = i,
                title = temp.County.ToString()
                });
            i++;
 }

Thanks!

EDIT: Forgot to mention that the entities are coming from a view, which would make sense given the comment about the primary key.

Upvotes: 3

Views: 1706

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062755

Have you perhaps misconfigured a primary key, such that EF thinks something is a primary key, when in fact each row has the same value? Importantly, EF is obliged to give you the same instance every time it sees an object with the same type+primary key that it has seen before.

So if all your records look like:

id   | title | ...
-----+-------+-------
1    | Foo   | ...
1    | Bar   | ...
1    | Baz   | ...
...

and if EF thinks that id is a primary key, it will give you back the same object each time - so you'll see Foo, Foo, Foo...

Upvotes: 7

Related Questions