views:

213

answers:

1

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.

+7  A: 

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...

Marc Gravell
Nice one Marc. Nice creativity!
Alex James
This makes a whole lot of sense. The entities are in fact coming from a view, so my guess is that you are correct. This does, however, beg the question of how do you iterate over entities coming from a view. Any ideas?
What does the view look like? Is there duplicated data in something like an id column? I'll take a quick look in my local IDE to see if there are any obvious options...
Marc Gravell
In the View, set Entity Key to "False" for any columns that don't **uniquely** identify that row. This is also visible as a yellow key icon, which should only be set against the true primary key (if any) for that record.
Marc Gravell