Doubt to Bring a Details of Two Tables MVC5 Entityframework 6.2

Asked

Viewed 53 times

0

I’m studying ASP.NET MVC5 for college, and I came across a problem, I have three tables: Usuario, PessoaFisica, Endereco.

My problem is this, when I’m right in the system, I can only bring the information (Details) user, which is e-mail and password.

I would also like to bring information from PessoaFisica and Endereco, which has connection to this table from the FK usu_id.

Someone could give me a light?

My code so far is this on Controller

public ActionResult Details(int? id)
{
    Usuario usuario = db.Usuario.Find(id);
    if (usuario != null)
    {
        Informacao inf = new Informacao();
        inf.Email = usuario.Email;
        inf.Senha = usuario.Senha;
        //Falta Tabela de Endereço e Pessoa Física
        return View(inf);

    }
    return View();
}

I thought to put after the inf.Senha one:

Endereco end = db.Endereco..Where(x => usu.Id == id).ToList().FirstOrDefault();

Then repeat and get the information from PessoaFísica, but I don’t think it’s the best way.

Someone could give me a light or a north?

2 answers

0

You can create an entity that has the details you want to display (User, Person and address) and then populate that entity with a query using Linq. You already have an example of something similar here.

Just stay tuned to the way you build your queries. It may happen that the query gets a bad performance. Check out the documentation to avoid these scenarios.

  • I don’t know how your time is, but it would be good to try to create a layer to not leave your queries and validations in your controller.

0

In fact this happens because of Lazy Loading which, by default, is enabled in EF. Lazy Loading is used to load only the requested data, so any relation is ignored unless explicitly requested. To get around this you can follow the example shown in the documentation

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .ToList();
}

Browser other questions tagged

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