【问题标题】:Join models in asp.net mvc application在 asp.net mvc 应用程序中加入模型
【发布时间】:2014-01-30 14:03:23
【问题描述】:

在带有 MVC5 和 EntityFramework6 的 ASP.NET Visual Basic 项目中,我有 2 个模型 在 SQL Server 数据库中,一个名为 User,具有列 (id,name,surname,companyid),另一个名为 Company(id,name,address)。

如何将这两个模型加入另一个模型并创建一个控制器,在视图中显示该连接的结果?

【问题讨论】:

    标签: asp.net asp.net-mvc vb.net entity-framework model


    【解决方案1】:

    这里有解决方案 -

    来自 EF 的模型 -

    然后你可以有如下的 ViewModel -

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

    Controller Action 可以是 -

    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);
        }
    }
    

    索引视图将是 -

    @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>
    

    当你执行代码时,你的输出将是 -

    【讨论】:

      【解决方案2】:

      如何在另一个模型中加入这两个模型 --> 使用 ViewModel

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

      由于您的 UserInfo 有一个外键 CompanyId,希望您的 User 类可能有一个由 EF 生成的名为 Company 的属性。如果没有,您可以将其添加到您的视图模型中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-19
        • 2022-11-01
        • 2013-11-30
        • 1970-01-01
        • 2017-09-22
        • 2011-02-04
        • 2010-10-27
        相关资源
        最近更新 更多