实体框架仅返回一个值,但列表大小正确
实体框架仅返回一个值,但列表大小正确
我有一个没有主 ID 的表,我需要获取或选择其中的所有值。
我看到的是,当我使用 linq 进行选择时,对象的数量是正确的,但它一遍又一遍地是第一行。
我只是在做这样的事情
List<MyValueType> valuesInDB = myDb.MyValueTypes.ToList();
问题是我可能会得到数千行(这是正确的),但这些行都具有相同的确切数据。
我正在使用 VS 2010 并使用向导来创建我的 EF 对象。
Entity framework returning only one value but the list size is correct
I have a table that does not have primary id and I need to get or select all the values in it.
What I see is when I do the selection with linq the number of objects is correct but it is the first row over and over.
I am simply doing something like this
List<MyValueType> valuesInDB = myDb.MyValueTypes.ToList();
Problem is I may get thousands of rows (which is correct) but the rows all have the same exact data.
I am using VS 2010 and used the wizard to create my EF object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是实体框架无法在没有密钥的情况下与实体一起工作。因此,如果您的表未指定键,实体框架将推断 自己的。 EF 创建的键由所有不可为空的非二进制列组成。
因此,如果您的实体中有单个不可为空的列,并且只有非常小的值集(例如枚举),您将只能“每个值”加载单个实体。原因是上下文和状态管理器的内部实现使用身份映射模式。当从数据库中检索数据记录时,EF 将首先检查实体键,并尝试在其内部存储中查找具有相同键的对象。如果找到一个对象,它将使用该对象而不是检索到的数据记录(尽管数据不同)。如果未找到具有该密钥的对象,则会具体化新对象并将其添加到内部存储中。
这就是身份映射的目的 - 具有给定键的对象应该由每个上下文仅创建一次。身份映射是 ORM 中的核心模式。
我也在这个问题中写了有关身份映射的文章。
The problem is that entity framework is not able to work with entity without a key. So if your table doesn't specify a key, entity framework will infer its own. The key created by EF is composed of all non-nullable non-binary columns.
So if you for example have single non-nullable column in your entity which have only very small set of values (like enum) you will be able to load only single entity "per value". The reason is an inner implementation of the context and the state manager which uses Identity map pattern. When data record is retrieved from database, EF will first check an entity key and tries to find an object with the same key in its internal storage. If an object is found it will use that object instead of data record retrieved (despite of different data). If an object with the key is not found a new object is materialized and added to internal storage.
That is the purpose of Identity map - object with given key should be created only once by each context. Identity map is core pattern in ORM.
I wrote about Identity map also in this question.
我建议在 EDM 的 Designer.cs 文件中搜索“警告”一词。它可能会告诉您实体框架是否对您的表有任何问题。
在没有表格设计的情况下,我真的无法发表太多评论。我尝试复制您的问题,但未能成功。这是我所做的:
如果你能分享你的表的创建脚本那就更好了。
I would suggest searching for the word "Warning" in your EDM's designer.cs file. It might tell you if Entity Framework is having any issues with your table.
I really can't comment much in the absence of the table design. I tried replicating your problem but wasn't able to do so. Here is what I did:
It would be better if you can share the create script for your table.