问题
Using MVC 4 with EF code First. When doing linq to EF selects statements, the collections are being populated with what seems like the last record's data. And what's weirder, only some of the properties are repeated where others are not. It is best to show you by example:
Using this query returns the proper data:
var orders = db.Orders.ToList();
OrderID OrderTotal Name
1 215.00 Bob
2 415.00 Mark
3 315.50 Ralph
When I filter the Orders entity by a SubscriberID, which is a foreign key, like so:
var orders = db.Orders.Where(s => s.SubscriberId == 2).ToList();
The data end up looking like this:
1 315.50 Bob
2 315.50 Mark
3 315.50 Ralph
Notice how the OrderTotal is repeated but the names stay the same. Please note that this is not a view issue. When I look at the data in the collection while debugging in the controller, this is what I see. This does not appear to be the only place this is happening. I am seeing something similar with more complicated models - but I thought I'd start with the simplest sample. Thanks!
回答1:
The problem was caused when I was setting default values on my models. Apparently using static was incorrect. So:
[ReadOnly(true)] [Display(Name = "Sub total")] private static decimal _OrderSubTotal = 0; public decimal OrderSubTotal { get { return _OrderSubTotal; } set { _OrderSubTotal = value; } }Should be written as
[ReadOnly(true)] [Display(Name = "Sub total")] private decimal _OrderSubTotal = 0; public decimal OrderSubTotal { get { return _OrderSubTotal; } set { _OrderSubTotal = value; } }来源:https://stackoverflow.com/questions/15815533/entity-framework-is-not-returning-the-proper-data-it-is-repeating-data-from-a-s