Find information on more than one table

2

In my project I currently have 3 tables: Students, Occurrences and Users. In them I have views and controllers .

So far so good. My relationships are: Students & Occurrences (1, N) / Occurrences & Users (N, 1).

My problem is that in action Details, both Occurrences and Users, I can not show some relationship information. In the case of occurrences I can not show the name of the student and neither of the user (but in the Index, I can show these names), and in the users I can not show the name of the student (which would have to be shown by the fact of coming from the relationship of Students & Occorrences).

Here is my code that is in action that shows all the information, except those mentioned previously:

ActionResult Controller Occurrences

    public ActionResult Detalhes(long? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Ocorrencia ocorrencia = db.Ocorrencias.Find(id);

        if (ocorrencia == null)
        {
            return HttpNotFound();
        }
        return View(ocorrencia);
    }

ActionResult Controller Users

    public ActionResult Detalhes(long? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        //Usuario usuario = db.Usuarios.Find(id);
        Usuario usuario = db.Usuarios.Include(o => o.Ocorrencias).AsNoTracking().FirstOrDefault(u => u.UsuarioID == id);

        if (usuario == null)
        {
            return HttpNotFound();
        }
        return View(usuario);
    }

Could anyone help me? Is this the case of a join?

    
asked by anonymous 14.11.2014 / 03:40

1 answer

2

Do not use Find . Find brings only the requested record, without the relationships between the other entities.

Change to FirstOrDefault , and use Include to load related data:

var ocorrencia = db.Ocorrencias
                 .Include(o => o.Aluno)
                 .Include(o => o.Usuario)
                 .FirstOrDefault(o => o.OcorrenciaID == id);

For Usuario , you do not need to use AsNoTracking() . The rest is correct:

var usuario = db.Usuarios.Include(o => o.Ocorrencias).FirstOrDefault(u => u.UsuarioID == id);

Do not forget to include using System.Data.Entity; in the Controllers header.

    
14.11.2014 / 05:17