Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 838
skysurfer Avatar asked Aug 04 '17 11:08

skysurfer


1 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; }
...
like image 77
Manfred Wippel Avatar answered Nov 15 '22 09:11

Manfred Wippel