Elad Benda
Elad Benda

Reputation: 36654

Adding new item with EF with identity column

How can I add a new entity with EF where I have Id column which is defined as identity in the database ?

I get the following error:

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

But I cannot set the Id to null, as it's an int in the database (not even nullable)

My function is:

    public Conduit.Mam.MaMDBEntityFramework.AppsData Add(Conduit.Mam.MaMDBEntityFramework.AppsData item)
    {   
        maMdbEntities.AddToAppsDatas(item);

        maMdbEntities.SaveChanges();

        return item;
    } 

Upvotes: 0

Views: 460

Answers (3)

Yograj Gupta
Yograj Gupta

Reputation: 9869

If you are setting Id with any integer value except zero than remove that initialization or set it to zero.

As the exception is clearly saying that you have a value for your Id column, which is identity column.

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

Exception

String or binary data would be truncated. The statement has been terminated

only comes when your sending data length is greater than db table column datatype lenght.

Upvotes: 2

Dmitry
Dmitry

Reputation: 31

String or binary data would be truncated. The statement has been terminated.

This means: data you want to insert in the column more then column size. Increase column size in db.

Upvotes: 2

Elad Benda
Elad Benda

Reputation: 36654

I had to make this attribute identity in the edmx as well

Upvotes: 2

Related Questions