I want to retrieve all rows which satisfying a condition. But when i tries only row count is correctly showing on debugging and the very first row value is repeatedly getting. following is my code
var data = (from jlist in entity.JobDetails
where jlist.JobID == QJobID
select jlist).ToList();
only first row value is showing in the var data. I have more than 1 items to be displayed
Repetitive identical objects are nearly always a tell-tale of primary key inaccuracies: the PK that EF knows about does not uniquely identify the actual records in the database. This frequently happens when views are mapped to EF models, because a view is just a stored query that maybe doesn't even bother about unique identification.
In your case you changed the single primary key to a composite key, without EF knowing it, or you only told EF that JobID was the primary key.
When EF materializes an entity object it creates an EntityKey for it that has a reference to the entity. These EntityKey have to be unique, otherwise the change tracker crashes. So when there are two entities, identified by { 1, 1 } and { 1, 2 }, while EF only looks at the 1, EF will use an existing entity key for the second entity. The weird part, I think, is that EF still decides to materialize a second instance matching this entity key. If it wouldn't you'd have seen only one JobDetails record which might have better directed your suspicions to the right spot.
Related
Without getting into the "why", just understand this in inherited and what I have to work with :)
I have an EF6 edmx mapped to a view. There is no identifying column on it, so in order for EF to map the entity, the first not-null column was selected as the PK. The original thought behind this was it is read only no updates or deletes would be done. There is no filtering (ODATA sits on top of this), and the only - and I mean only - way this is used is select top N * from the entity.
There are 4 records in the view.
TypeCode | Contact | UserID | LocaleID | EntityName
---------------------------------------------------------
1 6623 1032 9 Jane
1 6623 1032 9 Jane
1 6623 1032 9 John
1 6623 1032 9 John
The problem I am seeing is that EF is mapping all 4 rows the same. All "John" names above become "Jane"
OK, putting aside the design decision, and the fact there is no identifying record on the view, why is EF mapping the last two rows wrong? My initial thought is that since the "PK" is set as TypeCode It doesn't know how to do it. But why would it be using the key column when just reading results from the database? I would have thought it only mattered for updates and deletes
If you query data by Entity Framework, the default behavior is that each materialized entity is tracked by its unique key. The unique key consists of any properties you told EF to use as key, or, alternatively, it inferred as key properties (TypeCode in your case). Whenever a duplicate entity key tries to enter the change tracker, an error is thrown telling that the object is already being tracked.
So EF simply can't materialize objects having duplicate primary key values. It would compromise its tracking mechanism.
It appears that, at least in EF6, AsNoTracking() can be used as a work-around. AsNoTracking tells EF to just materialize objects without tracking them, so it doesn't generate entity keys.
What I don't understand is why EF doesn't throw an exception whenever it reads duplicate primary key values. Now it silently returns the same object as many times as it encounters its key value in the SQL query result. This has caused many many people to get confused to no end.
By the way, a common way to avoid this issue is by generating temporary unique key values to the view by using ROW_NUMBER in Sql Server. That's good enough for read-only data that you read once into one context instance.
I'm using Entity Framework 6 with Code First on an SQL server. Today, with my greatest surprise, I received an exception Sequence contains more than one element on a a simple query by ID (in my domain, the primary Key of each object). After debugging, I found that in my database 2 identical entities with the same Primary Key exist.
Now, I have no idea how that could happen, but my biggest problem right now is how to solve the issue: I cannot just delete them both, since they are 2 users with important data associated to them. So I tried to remove just one, but I receive an exception due to the fact that some other object references this user (and again, I cannot delete those objects because they contain important data).
var users = _userService.GetAllBy().ToList();
var duplicatedUsers = users.Where(x => users.Count(y => y.Id == x.Id) > 1);
foreach (var user in duplicatedUsers)
{
try
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
catch (Exception e)
{
// it always enters here because of the foreign keys
}
}
Basically, since the 2 identical objects have the same foreign key, they also share the same relationships with the other related entities. Therefore, I cannot just simply delete one of them because that causes an exception. But I don't want to delete them both either, because that would cause data loss. Any suggestion?
If sql server you can use a window function to identify a row and delete it that way -- see How do I delete duplicate rows in SQL Server using the OVER clause? as an example. Alternatively, if the table has more columns that what is defined in the key, you can hopefully use the other columns to more uniquely identify the "duplicate" row.
If it is, say, Oracle, you can get the ROWID of the row (just do a select rowid, t.* from table_name_here t WHERE conditions_here) and then when you find the right rowid, just do a straight DELETE FROM table_name WHERE rowid = XYZ123
Without getting into the "why", just understand this in inherited and what I have to work with :)
I have an EF6 edmx mapped to a view. There is no identifying column on it, so in order for EF to map the entity, the first not-null column was selected as the PK. The original thought behind this was it is read only no updates or deletes would be done. There is no filtering (ODATA sits on top of this), and the only - and I mean only - way this is used is select top N * from the entity.
There are 4 records in the view.
TypeCode | Contact | UserID | LocaleID | EntityName
---------------------------------------------------------
1 6623 1032 9 Jane
1 6623 1032 9 Jane
1 6623 1032 9 John
1 6623 1032 9 John
The problem I am seeing is that EF is mapping all 4 rows the same. All "John" names above become "Jane"
OK, putting aside the design decision, and the fact there is no identifying record on the view, why is EF mapping the last two rows wrong? My initial thought is that since the "PK" is set as TypeCode It doesn't know how to do it. But why would it be using the key column when just reading results from the database? I would have thought it only mattered for updates and deletes
If you query data by Entity Framework, the default behavior is that each materialized entity is tracked by its unique key. The unique key consists of any properties you told EF to use as key, or, alternatively, it inferred as key properties (TypeCode in your case). Whenever a duplicate entity key tries to enter the change tracker, an error is thrown telling that the object is already being tracked.
So EF simply can't materialize objects having duplicate primary key values. It would compromise its tracking mechanism.
It appears that, at least in EF6, AsNoTracking() can be used as a work-around. AsNoTracking tells EF to just materialize objects without tracking them, so it doesn't generate entity keys.
What I don't understand is why EF doesn't throw an exception whenever it reads duplicate primary key values. Now it silently returns the same object as many times as it encounters its key value in the SQL query result. This has caused many many people to get confused to no end.
By the way, a common way to avoid this issue is by generating temporary unique key values to the view by using ROW_NUMBER in Sql Server. That's good enough for read-only data that you read once into one context instance.
I have found that LINQ to Entities needs a primary key on the table in order to return correct results. Without it, I get the expected number of rows but including duplicates (and accordingly, missed rows). This problem is described here and here, and I consider it to be a bug.
In one of my tables, each row is unique but I cannot create a compound key across all fields because nullable columns cannot be used in primary keys (again, I consider this a SQL Server limitation).
So... how can I get correct results when selecting from this table using LINQ to Entities? I believe the "key" may be to create an "Entity Key" across all columns in the Visual Studio model designer but I'm not sure how to do this. Setting Entity Key = true on nullable columns throws an exception.
At one stage I gave up and added an identity int column with auto-increment enabled and used that as PK, which solved the issue, but I had to throw this out because of the volume of data being deleted/inserted all the time (it's not possible to simply reset the auto-increment counter on a schedule because not all of the rows are deleted, causing clashes).
My last resort will be to add a bigint identity column as PK, get rid of the auto-increment seed value resetter and hope it lasts "long enough" for the life of the application, but I'm not comfortable with this. (Edit: OK... it will last long enough. My main concern is performance)
I'm writing a quick app using LINQ to SQL to populate a db with some test data and had a problem because one of the tables had no primary key as described by this bloke Can't Update because table has no primary key.
Taking the top answer I added the IsPrimaryKey attribute to an appropriate column and the app worked even though the I haven't changed the db table itself (i.e. there is still no primary key).
I expect it will be ok for my current intentions but are there any side effects which may come from having a table without a primary key seen as having one by the LINQ object?
(I can only think it might be a problem if I tried to read from a table (or populate to a table) with data where the 'primary key' column has the same value in more than one row).
When using an ORM framework, you can simulate keys and foreign keys at ORM level, thus "hiding and overriding" the database defined ones.
That said, that's a practice that I wouldn't recommend. Even if the model is more important than the database itself, the logical structure should always match. It is ok doing what you did if you're forced to work with a legacy database and you don't have the possibility to fix it (like adding the PK on the table). But try to walk the righteous path everytime you can :)
Tables without a PK = Pure Evil.
Basically if all the table updates go through the LINQ object you should be fine. If you have a DBA that decides to modify data directly though SQL then you can quickly run into issues if he duplicates a row with the same PK value.