0

What to do when the data is inserted in the database, the "ID" column is autonumber. I tried this:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdMema { get; set; }
public string Autor { get; set; }
public int? Like { get; set; }
public int? Dislike { get; set; }

Properties "Memy" table:

CREATE TABLE [dbo].[Memy] (
    [Id_mema] INT  NOT NULL IDENTITY,
    [autor]   TEXT NULL,
    [like]    INT  NULL,
    [dislike] INT  NULL,
    PRIMARY KEY CLUSTERED ([Id_mema] ASC)
);

When I try to insert data, then I see:

"SqlException: Cannot insert explicit value for identity column in table 'Memy' when IDENTITY_INSERT is set to OFF."

How to resolve this?

kamilm758
  • 51
  • 5

2 Answers2

1

You have auto-increment field Id_mema. Auto-increment is set with IDENTITY keyword. Exception says it:

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

When you insert data to your table, you cannot give value to identity field. DB engine gives value to Id_mema-field (auto-increment 0,1,2,3..)

Following should work (straight sql):

INSERT INTO MEMY(autor, like, dislike) values ('text',1,0)

and in case of entity framework, be sure not to set Id_mema in your code.

Risto M
  • 2,919
  • 1
  • 14
  • 27
0

You don't need to pass Id_mema value when you going to insert values like below.

INSERT INTO MEMY values ('kamilm',10,5);

OR

if you don't want to auto incremented column then change the DatabaseGeneratedOption.Identity to DatabaseGeneratedOption.None it will allow you to insert value in Id(Key) column.

 [Key]
 [DatabaseGenerated(DatabaseGeneratedOption.None)]
 public int IdMema { get; set; }
 public string Autor { get; set; }
 public int? Like { get; set; }
 public int? Dislike { get; set; }
Umair Anwaar
  • 1,130
  • 9
  • 27