EF Core Complex Object Insertion with WebAPI

0

I'm developing a WebAPI (.NET) application with EntityFramework Core. I have implemented the following entities:

Pais.cs

public class Pais
{
    [Key]
    public int Id { get; set; }
    [MaxLength(100), Required]
    public string Descricao { get; set; }
}

Status.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 insert 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.

I think the system is trying to insert the country that is related to the city of JSON, but I do not understand why.

    
asked by anonymous 29.06.2017 / 15:10

1 answer

2

The EntityFramework is trying to add a new Pais , and since it is not explicit that it is EF that should create the IDs, EF is waiting for the Country ID to be null or 0 , repository's responsibility to create this ID.

However, this is not your intention. You just want to add Cidade . A workaround is, before adding the new record Cidade in EF, query by Estado and bind to the new object:

var estado = dbContext.Estados.Single(estado => estado.Id == novaCidade.Estado.Id);
novaCidade.Estado = estado;
dbContext.Cidades.Add(novaCidade);
dbContext.SaveChanges();

So your EF will know that the new Cidade is directly related to an existing parent record in your repository.

But to really hit it all, check out how you're setting up your EF. Consider maybe, or add a EstadoId to the Cidade class, or create different repository models within the scope of the repository - which will require a lot of development effort, but the result is great.

    
29.06.2017 / 15:13