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

entity-framework-core

Question

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.

1
5
8/4/2017 11:09:30 AM

Popular Answer

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; }
...
1
6/5/2019 9:40:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow