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.
Related
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.
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.
The picture show relation with two tables in my database;
Well as you can see there's a field called "DeviceTypeID" in the right side table.
Normally EF adds CompanyTypeID column to the ServiceLaburDefinitions model but it's disappeared last time I updated model from the database.
I am searching for a solution for a couple of hours but not able to find any solution. Could anyne suggest a solution?
Thanks.
ServiceLaburDefinitions is the depend entity and has the DeviceTypeID foreign key property defined.
So Entity Framework creates a navigation Key under the hood between the 2 tables based on DeviceTypeId key.
You can see for example how a navigation key is created also in the following example between the foreign key and the primary key
More information about navigation properties can be found here
When you create the model from the database, there is a checkbox marked "Include Foreign Key columns In The Model" - Make sure this is checked.
If I have an entity in EF and I also have foreign key property in that entity. Now I want to update related record. If I use both Foreign Key Association and Independent Association, Then which will be preferred by Entity Framework and why ?
Case : Suppose If I assign different entity to navigation property and different enityId in foreign key property. Then what will be saved in database ?
I think the foreign key in your case. Independent key just for the table's itself
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.