EF Core set Id to Int.MinValue and try to insert in database

Viewed 1417

I am using EF Core and I have a problem when I save a new entity.

Here is my model class

[Column("Id")]
public int ID { get; set; }
[Required]
[Column("Pratica", TypeName = "varchar(10)")]
public string PRATICA { get; set; }
[Column("Anno")]
public int ANNO { get; set; }
[Required]
[Column("Variante", TypeName = "varchar(2)")]
public string VARIANTE { get; set; }

Here I create and initialize a new PRAT object:

var prat = new PRAT();
prat.PRATICA = "Prova";
prat.ANNO = 2000;
prat.VARIANTE = "0";
context.PRAT.Add(prat);
context.SaveChangesAsync();

Just after the context.PRAT.Add(prat) line if I check prat.ID member I get something like -2147482647

After context.SaveChangesAsync I get the error "Cannot insert explicit value for identity column in table 'Prat' when IDENTITY_INSERT is set to OFF"

This is the generated SQL statement:

INSERT INTO [Prat] ([Id], [Anno], [Pratica], [Variante]) VALUES (@p0, @p1, @p2, @p3);

As you can see the Id Field is added to the list of fields, but this field is Identity!

If, before context.SaveChangesAsync() I set

prat.ID = 0

the generated SQL Statement is

INSERT INTO [Prat] ([Anno], [Pratica], [Variante]) VALUES (@p0, @p1, @p2);

And all works fine.

Thank you.

2 Answers

I think you need to configure your model with the DatabaseGenerated attribute, or configure it with fluent api

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

The primary key property is of type int, by convention EF Core assumes that the database will use the SQL IDENTITY command to create a unique key when a new row is added. So you must define your database column as identity column.

Related