0
I am developing a Webapi (.NET) application with Entityframework Core. I implemented the following entities:
Pais.Cs
public class Pais
{
[Key]
public int Id { get; set; }
[MaxLength(100), Required]
public string Descricao { get; set; }
}
Estado.Cs
public class Estado
{
[Key]
public int Id { get; set; }
[Required]
public virtual Pais Pais { get; set; }
[Required]
public string Descricao { get; set; }
public string Sigla { get; set; }
}
City.Cs
public class Cidade
{
[Key]
public int Id { get; set; }
public virtual Estado Estado { get; set; }
public string Descricao { get; set; }
}
When trying to enter a new record with JSON below:
{
"descricao": "Ribeirão Preto",
"estado": {
"id": 1,
"pais": {
"id": 1,
"descricao": "Brasil"
},
"descricao": "São Paulo",
"sigla": "SP"
}
}
I have the following return Cannot insert explicit value for identity column in table 'Pais' when IDENTITY_INSERT is set to OFF.
It seems to me the system is trying to insert the Country that is related to the city of JSON, but I’m not sure why.
So, but I’m not passing the city id in the json above. So wasn’t it supposed to generate automatically? And from what I understand of the error, he is trying to enter the country, and this already has the informed id.
– Thiago
Remembering I’m trying to add a new city.
– Thiago
I edited the answer, it should be clearer now.
– Thiago Lunardi
Show, now it worked out. I’d just like to know one more thing. Do I really have to consult the Status object again? Because as you already pass the information on JSON you did not see the need to consult. Out that this may affect the performance of the application or not?
– Thiago
Yes you can, but that’s because of your architecture. If you create a property
EstadoId
inCidade
and let the EF know that this is a foreign key, you don’t need the first query.– Thiago Lunardi