实体框架未返回正确的数据。它正在重复来自单个记录的数据 [英] Entity Framework is not returning the proper data. It is repeating data from a single record

查看:227
本文介绍了实体框架未返回正确的数据。它正在重复来自单个记录的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先将MVC 4与EF代码一起使用。
在对EF select语句执行linq时,将使用看起来好像最后一条记录的数据填充集合。奇怪的是,只有某些属性重复出现,而其他属性则没有。最好通过示例向您显示:

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订单总名称

OrderID OrderTotal Name

1225.00

2 415.00马克

2 415.00 Mark

3 315.50拉尔夫

3 315.50 Ralph

当我通过SubscriberID过滤Orders实体时,SubscriberID是一个外键,像这样:

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鲍勃

1 315.50 Bob

2 315.50马克

2 315.50 Mark

3 315.50拉尔夫

3 315.50 Ralph

请注意如何重复OrderTotal,但名称保持不变。请注意,这不是视图问题。当我在控制器中调试时查看集合中的数据时,这就是我看到的。这似乎不是发生这种情况的唯一地方。我发现更复杂的模型也有类似的现象-但我认为我将从最简单的示例开始。谢谢!

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!

推荐答案

问题是我在模型上设置默认值时引起的。显然使用static是不正确的。因此:

The problem was caused when I was setting default values on my models. Apparently using static was incorrect. So:

应写为

这篇关于实体框架未返回正确的数据。它正在重复来自单个记录的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆