Entity Framework is not returning the proper data. It is repeating data from a single record

匆匆过客 提交于 2019-12-12 03:57:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!