ASP.net MVC5显示来自已加入ViewModel的数据

时间:2018-07-13 00:54:58

标签: c# asp.net asp.net-mvc entity-framework

我在这里有一个名为UsersViewModel的ViewModel。它与一个名为userextended的表连接。

public class UsersViewModel
{
    public ApplicationUser aspNetUsers { get; set; }
    public AspNetUsersExtended aspUsersExtended { get; set; }
}

我坚持将表加入表并将其推出视图的操作。 这是我的控制器:

private ApplicationDbContext dbContext = new ApplicationDbContext();
    // GET: Users
    public ActionResult Index()
    {

        return View();
    }

    private List<UsersViewModel> GetUsers()
    {
        var userStore = new UserStore<ApplicationUser>(dbContext);
        List<UsersViewModel> uvml = new List<UsersViewModel>();
        AspNetUsersExtended[] usersExtended = dbContext.AspNetUsersExtended.ToArray();

        return uvml;
    }

我已经看过一些示例,它们在其中执行sql查询联接,但是我想知道viewmodel是否可以像模型中那样自动联接它?

已更新:

@model IEnumerable<ManagementStudio.ViewModels.UsersViewModel>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Users</h2>
@foreach (var item in Model)
{
    <p>@item.aspNetUsers.Id</p>
    <p>@item.aspNetUsers.Email</p>
    <p>@item.aspUsersExtended.Notes</p>
}

1 个答案:

答案 0 :(得分:0)

假设ApplicationUser和AspNetUsersExtended之间存在关系,则可以使用linq2sql方式将两个集合都加入,

var userStore = new UserStore<ApplicationUser>(dbContext);
List<UsersViewModel> uvml = (from user in userStore.Users
                                 join ext in dbContext.AspNetUsersExtended
                                 on user.X equals ext.X
                                 select new UsersViewModel
                                 {
                                     aspNetUsers = user,
                                     aspUsersExtended = ext
                                 }).ToList();

return uvml;

目前还没有机器可以测试,希望对您有所帮助。