Entity Framework Extensions: Can't BulkMerge entities with empty identity property - c#

I uses BulkMerge method of Entity Framework Extensions for insert/update large collections of entities. Entity table have identity column Id that used as a primary key. When I try to BulkMerge collection with several newly created entities (they have Id = 0 by default) it throws such exception: Violation of PRIMARY KEY constraint 'PK_Users'. Cannot insert duplicate key in object 'dbo.Users'. The duplicate key value is (0). Btw, BulkInsert method with same entities works fine. I tried to use options like AutoMapOutputDirection, InsertIfNotExists or MergeKeepIdentity but they were ineffective. Can anyone suggest the correct options for proper BulkMerge work or any other ways to solve issue?

Related

Entity Framework AutoIncrement

I created a simple code first entity for learn purpose. Does EF6 automatically select the property to auto-increment? Because I found that it appears to be doing this. Does it automatically select the primary key too?
My search on this question yielded answers to questions of how to switch the identity property using "Data Annotations" Source but that doesn't exactly answer my question.
Does EF6 automatically select the property to auto-increment?
What you are describing is an Identity column (auto increments) which is also a primary key.
So let's visit the documentation:
Code First Data Annotations
Entity Framework relies on every entity having a key value that is
used for entity tracking. One convention of Code First is implicit key
properties; Code First will look for a property named “Id”, or a
combination of class name and “Id”, such as “BlogId”. This property
will map to a primary key column in the database.
Note : the key will also be defined as Identity by default
There is a lot more to this and various ways to configure fields and tables, so I recommend reading the documentation thoroughly.

Prevent set null on delete in Entity Framework database-first

I have a database-first model using Entity Framework 6.2.0 which has the following association:
As you see, the OnDelete property on both ends is set to None. The corresponding relation in SQL server is shown below:
Although there is no explicit setting to set null on delete, when I try to remove an object from Plannings (primary table), EF sets all foreign key records in the table Waybill to null.
In the same database and model, I have the following foreign key and corresponding association:
All circumstances are the same as earlier. But in this case, when I try to remove an object from Products, it fails because of conflict with foreign key constraint (as I expect).
Why these two similar cases have different behavior? How can I completely disable set null on delete in my database-first model? I know that in code-first model, we can delete conventions using the following:
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
But I could not find any way to do this in database-first.

How to setting a model with table don't have any primary key column

On setting DbContext, we have
modelBuilder.Entity<Person>(app =>
{
app.ToTable("Person");
});
The EFCore throws an exception:
The entity type "Person" requires a primary key to be defined
But our Person table doesn't have any primary key column.
How to avoid this ?
EF Core doesn't support tables without primary keys (aka heaps). The reason is simple: it needs to be able to manipulate individual records, something that cannot be safely achieved without a primary key.
As a resolution, you can add a dummy column/primary key of type int/identity or guid/uniqueidentifier, and just ignore it.

Violation of Primary Key error when trying to insert record into SQL Server using Entity Framework

Violation of PRIMARY KEY constraint 'PrimaryKeyId'. Cannot insert duplicate key in object 'dbo.Table'. The duplicate key value is (xxx).\r\nThe statement has been terminated.
This has been occurring off and on for several weeks now, and every time I think I have it fixed, and it pops up a couple days later. I am using:
dbContext.Table.Add(myObject);
dbContext.SaveChanges();
This is in a using statement, trying to add an object with a current id of 0. The PrimaryKeyId is the identity in the table, and is set to auto-increment by 1. However, Entity Framework seems to be taking a random Id and trying to assign it to my object and then add said object to the database.
This only happens on this one table and this same process is used on many other tables without any problems. The table being acted on is set up identical to other tables where this process is being used without error. Any ideas as to what could be causing this? To clarify, Entity Framework appears to be attempting to assign an already existing Primary Key to a new object.
Solution to my specific problem: Tar and feather a DBA
Explanation: While running a lengthy/complex import script, our DBA set it up to reseed the table at x, which is way below the current value in the identity column. So there technically hasn't been a problem these past several weeks, it was just human error. This question could/should/maybe ought to be dragged out behind a woodshed and put out of its misery. The tarring/feathering is his suggestion by the way (I do not endorse abuse of coworkers without their consent).
In the event that this question isn't deleted, the recommended fix is to check the current identity value on the table by using
select ident_current('tableName')
and comparing it to the highest value in the table. Especially if there are manual imports/modifications being done through a script where the seed might be manually reset.
This should prove helpful (Particularly the paragraph I have made bold): Taken from Working with Entity Keys
Entity Keys and Added Objects
When a new entity is created, the Entity Framework defines temporary key and sets the IsTemporary property to true. When you call the SaveChanges method, the Entity Framework assigns a permanent key and sets the IsTemporary property to false.
If the corresponding column value is an identity that is generated in the database, set the StoreGeneratedPattern attribute of the property element of an entity in the storage model to Identity. When the Entity Data Model tools generate a data model from an existing data source, the StoreGeneratedPattern attribute is added to each property element (CSDL) element that represents an identity or a computed column in the data source. The Entity Framework replaces the value of the property in a temporary key with the identity value that is generated by the data source after SaveChanges is called.
The following details the internal process that replaces the temporary key with a permanent key that contains the server-generated values:
The entity object is constructed.
At this point the key properties all have default values, either null or 0.
The new object is added to the ObjectContext either by calling the AddObject method on ObjectContext or ObjectSet or by adding an object to the collection of objects on the "many" end of the relationship.
At this point, the Entity Framework generates a temporary key, which is used to store the objects in the ObjectStateManager.
SaveChanges is called on the ObjectContext.
An INSERT statement is generated by the Entity Framework and executed on the data source.
If the INSERT operation succeeds, server-generated values are written back to the ObjectStateEntry.
The ObjectStateEntry updates the object with the server-generated value.
When AcceptChanges is called on the ObjectStateEntry, a permanent EntityKey is computed by using the new server-generated values.
AcceptChanges is called automatically at the end of the SaveChanges execution, or when the SaveChanges method is called with the AcceptAllChangesAfterSave flag.
The ObjectStateManager replaces all instances of the temporary key with the new permanent key.

Save entity in Entity Framework without a primary key

Scenario:
Database first.
I have a table with no primary key set and I'm trying to make an update with Entity Framework.
This is the error message I keep getting:
The property 'inactive_date' is part of the object's key information and cannot be modified.
If I set the fields 'Entity Key' value to 'false' I get this error messge:
Modifications to tables where a primary key column has property 'StoreGeneratedPattern' set to 'Computed' are not supported. Use 'Identity' pattern instead. Key column: 'timestamp'. Table: 'plat12Model.Store.glchart'.
Would this be corrected if I created a primary key? Can I set a primary key in my code rather than on the database?
By default, EF will make tables without primary keys and views into read-only classes where every field is part of the composite key. You can modify the conceptual model to reflect the actual behavior as long as you retain a key value that EF will use for object tracking. As the error message states, you also need to make the columns no longer computed in order to update them as well.

Categories

Resources