asp.net mvc应用程序中的连接模型
在带有MVC5和EntityFramework6的ASP.NET Visual Basic项目中,我有两个模型 在SQL server数据库中,一个调用的用户具有列(id、名称、姓氏、公司id),另一个调用的公司(id、名称、地址)asp.net mvc应用程序中的连接模型,asp.net,asp.net-mvc,vb.net,entity-framework,model,Asp.net,Asp.net Mvc,Vb.net,Entity Framework,Model,在带有MVC5和EntityFramework6的ASP.NET Visual Basic项目中,我有两个模型 在SQL server数据库中,一个调用的用户具有列(id、名称、姓氏、公司id),另一个调用的公司(id、名称、地址) 如何将这两个模型连接到另一个模型中,并创建一个在视图中显示该连接结果的控制器?如何使用ViewModel-->将这两个模型连接到另一个模型中 public class UserViewModel { public User UserInfo{get;set;}
如何将这两个模型连接到另一个模型中,并创建一个在视图中显示该连接结果的控制器?如何使用
ViewModel-->将这两个模型连接到另一个模型中
public class UserViewModel
{
public User UserInfo{get;set;}
}
由于您的UserInfo有一个外键CompanyId
,希望您的用户类可能有一个由EF生成的名为Company
的属性。如果没有,您可以将其添加到视图模型中解决方案如下-
来自EF-
然后,您可以使用如下所示的ViewModel-
public class UserMiniViewModel
{
public string UName { get; set; }
public string CName { get; set; }
}
控制器动作可以是-
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);
}
}
公共类用户控制器:控制器
{
公共行动结果索引()
{
列表模型=新列表();
使用(SampleEntities entities=新的SampleEntities())
{
var结果=来自实体中的p。用户
选择新的UserMiniViewModel()
{
UName=p.名称,
CName=p.Company.CompanyName
};
model=results.ToList();
}
返回视图(模型);
}
}
索引视图将是-
@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>
@model IEnumerable
@{
ViewBag.Title=“Index”;
}
指数
@DisplayNameFor(model=>model.UName)
@DisplayNameFor(model=>model.CName)
@foreach(模型中的var项目){
@DisplayFor(modelItem=>item.UName)
@DisplayFor(modelItem=>item.CName)
}
当您执行代码时,您的输出将是-
@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>