实体框架仅返回一个值,但列表大小正确 [英] entity framework returning only one value but the list size is correct

查看:54
本文介绍了实体框架仅返回一个值,但列表大小正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体框架仅返回一个值,但列表大小正确

我有一个没有主ID的表,我需要获取或选择其中的所有值.

我看到的是,当我使用linq进行选择时,对象数是正确的,但它是一遍又一遍的第一行.

我只是在做这样的事情

List<MyValueType> valuesInDB = myDb.MyValueTypes.ToList();

问题是我可能得到数千行(这是正确的),但是所有行都具有相同的确切数据.

我正在使用VS 2010,并使用向导创建了我的EF对象.

解决方案

问题是实体框架无法在没有密钥的情况下使用实体.因此,如果您的表未指定键,则实体框架将推断自己的. EF创建的键由所有不可为空的非二进制列组成.

因此,例如,如果您的实体中只有一个非空列,而该列只有很小的一组值(如枚举),那么您将只能按每个值"加载单个实体.原因是上下文和使用标识映射模式的状态管理器的内部实现.从数据库中检索数据记录时,EF将首先检查实体密钥,然后尝试在其内部存储中查找具有相同密钥的对象.如果找到一个对象,它将使用该对象而不是检索到的数据记录(尽管有不同的数据).如果找不到带钥匙的对象,则会物化一个新对象并将其添加到内部存储中.

这就是身份映射的目的-具有给定键的对象只能由每个上下文创建一次.身份映射是ORM中的核心模式.

我也在此问题中写了关于身份映射的信息. /p>

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.

解决方案

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.

这篇关于实体框架仅返回一个值,但列表大小正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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