Rilcon42
Rilcon42

Reputation: 9763

Cant insert identity column in EF, despite never changing the value

Im trying to update a table row using EntityFramework, without changing the ID column in my code. Why is it still telling me I can't insert an explicit value?

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

MY CODE

//mytbl context is initialized as _gc
var mymodel=_gc.mytbl.Where(x=>x.ID.ToString()=="1").FirstorDefault();
mymodel.otherfield=22;//sets a new value
_gc.Add(mymodel);
_gc.SaveChanges();

EF MODEL

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public int otherfield { get; set; }

SQL CREATE

CREATE TABLE [dbo].[tblLicenseGroups](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    ....
 CONSTRAINT [PK_tblSiteParentIDs] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Upvotes: 0

Views: 98

Answers (2)

ste-fu
ste-fu

Reputation: 7444

If you have retrieved and then modified the model with the same instance of the DbContext then you don't need to call the Add Method, just .SaveChanges()

The Update part happens automatically because EF tracks the changes that you have made to the objects from the database.

Upvotes: 2

Mark Davies
Mark Davies

Reputation: 1497

You are selecting out an existing record and attempting to add it again.

The error your receiving is probably because you have an identity field in your database, having [DatabaseGenerated(DatabaseGeneratedOption.Identity)] in your code suggests this is true.

You may want to try something to the affect of:

 var mymodel=_gc.mytbl.Where(x=>x.ID.ToString()=="1").FirstorDefault();
 mymodel.ID = 0;
 _gc.Add(mymodel);
_gc.SaveChanges();

The code is above is intending to register the model as a new version of itself, which should add a new record to your database table that is exactly the same as the first apart from the ID

Hope this helps

Upvotes: 0

Related Questions