从另一个数据库asp.net mvc中的另一个模型引用一个模型
本文关键字:模型 另一个 引用 一个 asp 数据库 net mvc | 更新日期: 2023-09-27 18:14:54
我有以下方法在我的控制器:
public ActionResult OwnerList()
{
var owners = (from s in db.Owners
orderby s.Post.PostName
select s).ToList();
var viewModel = owners.Select(t => new OwnerListViewModel
{
Created = t.Created,
PostName = t.Post.PostName,
Dormant = t.Dormant,
OwnerId = t.OwnerId,
});
return PartialView("_OwnerList", viewModel);
}
当运行这个时,我从owner变量中得到以下错误:
{"无效的对象名称'dbo.Post'。"}
我的模特是这些
owner数据库
public class Owner
{
public int OwnerId { get; set; }
[Column(TypeName = "int")]
public int PostId { get; set; }
[Column(TypeName = "bit")]
public bool Dormant { get; set; }
[Column(TypeName = "datetime2")]
public DateTime Created { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
public virtual Post Post { get; set; }
}
在People数据库
public class Post
{
public int PostId { get; set; }
[StringLength(50)]
[Column(TypeName = "nvarchar")]
public string PostName { get; set; }
[Column(TypeName = "bit")]
public bool Dormant { get; set; }
[StringLength(350)]
[Column(TypeName = "nvarchar")]
public string Description { get; set; }
public virtual ICollection<Contract> Contracts { get; set; }
public virtual ICollection<Owner> Owners { get; set; }
}
视图为:
@model IEnumerable<IAR.ViewModels.OwnerListViewModel>
<table class="table">
@foreach (var group in Model
.OrderBy(x => x.Dormant)
.GroupBy(x => x.Dormant))
{
<tr class="group-header">
@if (group.Key == true)
{
<th colspan="12"><h3>Dormant:- @group.Count()</h3></th>
}
else
{
<th colspan="12"><h3>Active:- @group.Count()</h3></th>
}
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.PostName)
</th>
<th>
@Html.DisplayNameFor(model => model.Created)
</th>
<th></th>
</tr>
foreach (var item in group
)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.PostName) @Html.HiddenFor(modelItem => item.OwnerId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Created)
</td>
<td>
@if (group.Key == true)
{
@Html.ActionLink("Make Active", "Dormant", new { ownerId = item.OwnerId })
}
else
{
@Html.ActionLink("Make Dormant", "Dormant", new { ownerId = item.OwnerId })
}
</td>
</tr>
}
}
</table>
我相信这是一些简单的东西,但我没有正确地做什么,让它从所有者引用Post ?
给定s.Post
是null
,你有实体框架的延迟加载禁用。要么启用延迟加载,要么显式加载navigation属性:
from s in db.Owners.Include(o => o.Post)
orderby s.Post.PostName
...
至于你的编辑,给定Owner.Post
是在一个不同的数据库,这是一个完全不同的问题。你可以在网上搜索一下,比如EF中的跨数据库查询和使用实体框架连接两个数据库中的表。要么在数据库级别链接它们(使用链接服务器或同义词和视图),要么在代码中修复它们(循环Owners
并查找它们的Post
)。