Detail of an item of different models in entity framework

1

I'm really new programming and I'm constantly encountering problems, I currently have a table where I put data related to students, house row has a button that allows me to see more information related to the student but there is also related information in other tables as per example the city table, state table and country table to which the student belongs. but this information is not how to show it in detail, because when the controller does the search, it only passes information about the UserSchool model and not the tables with which it is related. The student class is the following:

public class UserSchool
{

    [Key]
    public int UserId { get; set; }

    [Display(Name = "E-Mail")]
    [Required(ErrorMessage = "The field {0} is required")]
    [StringLength(50)]//only you can to write 50 characters
    [DataType(DataType.EmailAddress)]
    // [Index("UserNameIndex", Isnique = true)]
    public string EmailUser { get; set; }

    [Display(Name = "Nombres")]
    [Required]
    public string FirstNameUser { get; set; }

    [Display(Name = "Apellidos")]
    [Required]
    public string LastNameUser { get; set; }

    [Display(Name = "Full Name")]
    public string FullName
    {
        get { return string.Format("{0} {1}", this.FirstNameUser, this.LastNameUser); }
    }
    [Display(Name = "Telefono")]
    public string PhoneUser { get; set; }

    [Display(Name = "Direccion de residencia")]
    [Required]
    public string AddressUser { get; set; }

    [Display(Name = "Fecha de nacimiento")]
    [DataType(DataType.Date)]// para que nos muestre el calendario
    public DateTime DateBirthdayUser{ get; set; }


    [Display(Name = "Imagen")]
    public string PhotoUser { get; set; }

    [Display(Name = "Estudiante")]
    public bool IsStudentUser { get; set; }

    [Display(Name = "Profesor")]
    public bool IsTeacherUser { get; set; }

    [Display(Name = "Sistemas")]
    public bool IsSystemUser { get; set; }

    [Display(Name = "Numero de documento")]
    public string NumberDocumentUsers { get; set; }

    [Display(Name = "Tipo de documento")]
    public int TypeDocumentId { get; set; }
    public virtual TypeDocument TypeDocument { get; set; }

    [Display(Name = "Pais de nacimiento")]
    public int CountryId { get; set; }
    public virtual Country Country { get; set; }

    [Display(Name = "Departamento de nacimiento")]
    public int StateId { get; set; }
    public virtual State State { get; set; }

    [Display(Name = "Ciudad de nacimento")]
    public int CityId { get; set; }
    public virtual City City { get; set; }  




}

Country class

 public class Country
{

    [Key]
    public int CountryId { get; set; } 

    [Required]
    [Display(Name = "Nombre pais")]
    public string NameCountry { get; set; }

    public virtual ICollection<UserSchool> UserSchools { get; set; }


}

The State class

 public class State
{
    [Key]
    public int StateId { get; set; }

    [Required]
    [Display(Name = "Nombre Departamento")]
    public string NameState { get; set; }

    [Required]
    [Display(Name = "Pais")]
    public int CountryId { get; set; }
    public virtual Country Country { get; set; }

    public virtual ICollection<UserSchool> UserSchools { get; set; }


}

The city class

public class City     {         [Key]         public int CityId {get; set; }

    [Required]
    [Display(Name = "Nombre Ciudad")]
    public string NameCity { get; set; }

    [Required]
    public int StateId { get; set; }
    public virtual State State { get; set; }


    public virtual ICollection<UserSchool> UserSchools { get; set; }
}

The web controler that sends the information

public async Task<ActionResult> Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        UserSchool userSchool = await db.UserSchools.FindAsync(id);


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

The detail view where I want to show both student information and the name of the city, department name and country name.

<div class="panel-body">
    <table class="table table-hover">

        <tr>
            <td><b>Tipo Documento</b></td>
            <td>@Html.DisplayFor(model => model.City.NameCity)</td>
        </tr>
        <tr>
            <td><b>Numero Documento</b></td>
            <td>@Html.DisplayFor(model => model.NumberDocumentUsers)</td>
        </tr>
        <tr>
            <td><b>Nombre Completo</b></td>
            <td>@Html.DisplayFor(model => model.FullName)</td>
        </tr>
        <tr>
            <td><b>Correo electronico</b></td>
            <td>@Html.DisplayFor(model => model.EmailUser)n</td>
        </tr>
        <tr>
            <td><b>Direccion</b></td>
            <td>@Html.DisplayFor(model => model.AddressUser)</td>
        </tr>
        <tr>
            <td><b>Telefono</b></td>
            <td>@Html.DisplayFor(model => model.PhoneUser)</td>
        </tr>
        <tr>
            <td><b>Estudiante</b></td>
            <td>@Html.DisplayFor(model => model.IsStudentUser)</td>
        </tr>
        <tr>
            <td><b>Profesor</b></td>
            <td>@Html.DisplayFor(model => model.IsTeacherUser)</td>
        </tr>
        <tr>
            <td><b>Administrativo</b></td>
            <td>@Html.DisplayFor(model => model.IsSystemUser)</td>
        </tr>
        <tr>
            <td><b>Fecha de nacimiento</b></td>
            <td>@Html.DisplayFor(model => model.DateBirthdayUser)</td>
        </tr>
        <tr>
            <td><b>Lugar de nacimiento</b></td>
            <td>


            </td>
        </tr>
    </table>
    
asked by Jhon Alexander Jimenez Morales 15.11.2018 в 00:14
source

3 answers

1

Entity Framework by default does not bring the related entities when you make a query (if that were the case it would load the relationship of the relationship and end up loading the entire database!). You have to be explicit with which relationships you want to bring in the same query. One way is with Include

using System.Data.Entity;

// ...

var userSchool = await db.UserSchools
                         .Include(x => x.Country)
                         .Include(x => x.City)
                         .Include(x => x.State)
                         .FirstOrDefaultAsync(x => x.UserId == id);
    
answered by 15.11.2018 / 00:20
source
0

I tried to do it this way:

using System.Data.Entity;



var userSchool = await db.UserSchools
                     .Include(x => x.Country)
                     .Include(x => x.City)
                     .Include(x => x.State)
                     .FindAsync(id);

But I have this error:

    
answered by 15.11.2018 в 14:17
0

I recommend that you do not use the class that gives you the default Entity Framework, but that you map it to another ViewModel class to show the data you need.

This way, with EF, you bring with you all the data you need and you map it to this new ViewModel class that will help you to show the data in the view.

This is the best way to not complicate the life of the database model and the view.

I hope the advice serves you.

    
answered by 05.12.2018 в 12:38