我认为这是一段非常简单的代码,但结果令我感到困惑.我正在使用LINQ查询实体,然后迭代结果以创建数组.我正在观察进出数据库的流量,一切看起来都不错.当我复制LINQ发送到SQL的查询并
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++;
}
谢谢!
编辑:忘了提到实体来自一个视图,这对于主键的评论是有意义的.
您是否错误配置了主键,以至于EF认为某些东西是主键,而实际上每行具有相同的值?重要的是,EF每次看到具有与之前相同类型的主键的对象时,都必须为您提供相同的实例.所以如果你的所有记录都是这样的:
id | title | ... -----+-------+------- 1 | Foo | ... 1 | Bar | ... 1 | Baz | ... ...
如果EF认为id是主键,它每次都会返回相同的对象 – 所以你会看到Foo,Foo,Foo ……
