Entity Framework, code First, Database query

Asked

Viewed 50 times

1

Good evening, I have two classes to which one is an attribute of the other, Customer has Anamnese , when I search the database the return is the right customer, but the field Anamnese is null, and I want to recover this information.

Client class

public int Id { get; set; }
public Anamnese Anamnese { get; set; }

Anamnesis class

public int Id { get; set; }

my database is ok, client has his data and a foreign anamnesis key and can normally save a new client already with his anamnesis.

Method used to register for new anamnesis

public static void CadastrarAnamnese(Cliente clienteEntrada, Anamnese anamnese) {
        try
        {
            using (ConsultorioContext ctx = new ConsultorioContext())
            {
                Cliente cliente = ctx.Clientes.Find(clienteEntrada.Id);
                cliente.Anamnese = anamnese;
                ctx.SaveChanges();
            }
        }
        catch
        {

        }
    }
  • 2

    How is recovering, used the include!?

  • No, I tried it now but I couldn’t use it, could you give me an example?

  • 1

    var cliente = ctx.Clientes.Where(c => c.Id == id).Include(c => c.Anamnese).FirstOrDefault(); 

 Anamnese teste = cliente.Anamnese; with these two lines got thank you

1 answer

2


If you want to use the Lazy Loading just change the classes like this:

Client class

public int Id { get; set; }
public virtual Anamnese Anamnese { get; set; }

Anamnesis class

public int Id { get; set; }
public virtual ICollection<Cliente> Clientes{ get; set; }

This way, keeping the query the way you are already doing, will bring the data of Anamnese using Lazy Loading, automatically.

Or...

as already commented, you can use the include if you do not want to use Lazy Loading, change the query like this:

Cliente cliente = ctx.Clientes.Include(c => c.Anamnese).Find(clienteEntrada.Id);

Here at Sopt itself has some good answers about the Lazy Loading if you want to understand better before using it indiscriminately:

  1. How the Lazy Load Entity Framework works
  2. Entity - Disable Lazy Loading?

Browser other questions tagged

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