How to use EF Core with inheritance correctly and capture foreign key objects?

Asked

Viewed 105 times

0

I’m using the Entity Framework Core, and I have a model that uses heritage. I use the TPH (Table Per Hierarchy) pattern that maps all classes of the same super class in the same table and uses a discriminator column to distinguish them.

When I write a data into the database, all data goes correctly. But when I try to recover this data, I cannot capture the foreign key related objects.

public class Computador : ProdutoBase
{  
    public int CpuId { get; set; }
    [Required]
    public Processador Cpu { get; set; }
    [Required]
    public MemoriaRam Memoria { get; set; }
    public int HdId { get; set; }
    [Required]
    public HD Hd { get; set; }
    public int PlacaMaeId { get; set; }
    public PlacaMae PlacaMae { get; set; }
    [Required]
    public decimal Preco { get; set; }
    public int CodigoRef { get; set; }

    protected Computador() : base()
    {

    }

    public Computador(string marca, string modelo, decimal preco) : base()
    {
        Marca = marca;
        Modelo = modelo;
        Preco = preco;
    }

    public Computador(string marca, string modelo, decimal preco, Processador cpu, MemoriaRam ram, HD hd, PlacaMae placaMae) : base()
    {
        Marca = marca;
        Modelo = modelo;
        Preco = preco;

        Cpu = cpu;
        Memoria = ram;
        Hd = hd;
        PlacaMae = placaMae;
    }

    public void AddComponentes(Processador cpu, MemoriaRam ram, HD hd, PlacaMae placaMae)
    {
        Cpu = cpu;
        Memoria = ram;
        Hd = hd;
        PlacaMae = placaMae;
    }
}

Database

inserir a descrição da imagem aqui

Json

{"cpuId":1,"cpu":null,"memoria":null,"hdId":2,"hd":null,"placaMaeId":4,"placaMae":null,"preco":5000.00,"codigoRef":0,"id":5,"marca":"Dell","modelo":"Inspiron","urlImagem":"http://www.marcheartdevie.com.br/shop/img/p/br-default-home_default.jpg"}
  • How did you recover! lacked to pass this.

  • I am calling the get methods in a repository class through the Webapi controller. The methods in the repository base class are. public Iqueryable<Tentity> Getall() { Return Entity; } public Tentity Get(int id) { Return Entity.Find(id); }

  • If you can work with Include Advance loading ... !!! because GetAll() returns a IQueryable<T> and it is still made the query in the bank ... or else create another method to give a Include there are some possibilities

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.