4

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.

Maestro1024
  • 2,875
  • 8
  • 33
  • 51

2 Answers2

5

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.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
0

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:

  1. Created a table with no primary key but it had a unique key on an ID column. Entity Framework was able to infer a primary key and when I fetched the data, I not only got the correct number of rows but also the corrects data in those rows.
  2. Created a table with no primary key and no unique key. Also there was no column called ID. Entity Framework excluded this table in the EDM that was generated. Consequently I wasn't able to query this table at all.This was displayed as a warning in the EDM designer file.

It would be better if you can share the create script for your table.

Yasir
  • 1,535
  • 4
  • 21
  • 42