EF code: Cannot insert explicit value for identifier column in table "myTable" if IDENTITY_INSERT is set to OFF

Set the primary key for authentication in the database (SQL Server)

When using EF to insert data, I get an error

Cannot insert explicit value for identity column in table 'myTable' when IDENTITY_INSERT is set to OFF

with this particular entity, although I use the same approach with other objects to insert data and no errors with them.

public class MyTable { [Key/*,DatabaseGenerated(DatabaseGeneratedOption.Identity)*/] public int ID{get;set;} public string name {get;set;} public string type {get;set;} public string status {get;set;} public int country {get;set;} public DateTime start_date {get;set;} public DateTime due_date {get;set;} }` 

Request

  MyTable check= new MyTable(); check.name = checkName; check.type = "DB"; check.status = "New"; check.country = country; check.start_date = DateTime.Now; check.due_date = dueDate; db.myTables.Add(check); db.SaveChanges(); 

Updated :

After splitting the above line

 (DatabaseGenerated(DatabaseGeneratedOption.Identity)) 

he throws an exception

The dependent property in the reference binding maps to the store-created column. Column: 'ID'

+4
source share
4 answers

I'm not sure if this is also the case in your case .... but the second error says. You use your primary key as a foreign key in a way that is only valid for a property that has DatabaseGeneratedOption.None.

So, to use your primary key as a person, you can decorate it with DatabaseGeneratedOption.Identity
and in this case, it throws an exception because you cannot use the identifier for the relationship (use DatabaseGeneratedOption.None instead).

+3
source

Try the following:

 [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } 
+3
source

Try once:

 objDBEntities.MyTable.AddObject( new tblEmployee { check.name = checkName, check.type = "DB", check.status = "New", check.country = country, check.start_date = DateTime.Now, check.due_date = dueDate } ); objDBEntities.SaveChanges(); 

For more information: Entity Framework: how to add row data with support for the identity column in

0
source

Cannot insert explicit value for identifier column in table 'myTable' if IDENTITY_INSERT is set to OFF

The dependent property in the reference pointer maps to the column created by the store. Column: 'ID'

It seems that you did not determine the correct ratio of 1 ... 1 tables. if your pk is fk, make sure you use "[Key, ForeignKey (" Caller ")]. I hate how EF throws an exception. takes decays to find out the root causes .: (

if it is not fixed, the error message is associated with both tables. or for the main reason, it is always better to move your linked tables into a simple solution and check there so that you eliminate other facts. and check out convention, fluency api and data annotation.

0
source

Source: https://habr.com/ru/post/1438802/


All Articles