Search code examples
asp.net-mvcentity-framework-6ef-database-first

How i can send list of data from two tables to view?


I'm work in asp mvc application database first a broach So i have two tables Employee and Branch and i need to send list to view with Employee name and branch name that's my controller code

 public PartialViewResult List()
    {
        List<Employee> emp;
        using (var contxt = new EnglisCenterEntities())
        {

            var query = contxt.Employee.ToList();
            emp = query;
        }
        return PartialView(emp);
    }

and my view code is

@model IEnumerable<Insert.Models.Employee>

         <p>
      @Html.ActionLink("Create New", "Create")
         </p>
  <table class="table">
      <tr>

         <th>
        @Html.DisplayNameFor(model => model.EmpName)
        </th>
       <th>
        @Html.DisplayNameFor(model => model.Phone)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Username)
    </th>

    <th>
        @Html.DisplayNameFor(model => model.Branches.BranchName)
    </th>
    <th></th>
</tr>

     @foreach (var item in Model) {
   <tr>

    <td>
        @Html.DisplayFor(modelItem => item.EmpName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Phone)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Username)
    </td>

    <td>
        @Html.DisplayFor(modelItem => item.Branches.BranchName)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.IdEmp }) |
        @Html.ActionLink("Details", "Details", new { id=item.IdEmp }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.IdEmp })
    </td>
</tr>

}

But it doesn't work so how i can send branch name with employee data


Solution

  • Here is :

      public PartialViewResult List()
        {
            List<Employee> emp;
            using (var contxt = new EnglisCenterEntities())
            {
    
                var brands = contxt.Employee.Include("Branches").ToList();
               // var query = contxt.Employee.ToList();
                emp = brands;
            }
            return PartialView(emp);
        }
    

    Thanks guys :)