Join models in asp.net mvc application

in ASP.NET Visual Basic project with MVC5 and EntityFramework6 i have 2 model one called User with columns(id,name,surname,companyid) and one called Company(id,name,address) in a SQL server Database.

How Can i join this two model in another model and create a controller that shows in a view the results of that join ?

Answers


Here goes solution -

Model from EF -

Then you can have ViewModel as below -

public class UserMiniViewModel
{
    public string UName { get; set; }
    public string CName { get; set; }
}

Controller Action can be -

public class UsersController : Controller
{
    public ActionResult Index()
    {
        List<UserMiniViewModel> model = new List<UserMiniViewModel>();
        using (SampleEntities entities = new SampleEntities())
        {
            var results = from p in entities.Users
                          select new UserMiniViewModel()
                          {
                              UName = p.Name,
                              CName = p.Company.CompanyName
                          };
            model = results.ToList();
        }
        return View(model);
    }
}

Index View is going to be -

@model IEnumerable<MVC.Controllers.UserMiniViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.UName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CName)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CName)
        </td>
    </tr>
}

</table>

When you execute the code, your output is going to be -


How Can i join this two model in another model --> using ViewModel

public class UserViewModel
{
  public User UserInfo{get;set;}
}

since your UserInfo has a foreign key CompanyId, hope your User class might have a property called Company generated by EF. If not you can add it in your view model


Need Your Help

SQL Server 2008: Can a multi-statement UDF return a UDT?

sql-server tsql sql-server-2008 user-defined-functions user-defined-types

Is it possible that a multi-statement UDF return a User Defined Table Type, instead of a table that is defined within it's return param?