gpt4 book ai didi

c# - 从另一个数据库中的另一个模型引用一个模型asp.net mvc

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:42 25 4
gpt4 key购买 nike

我的 Controller 中有以下方法:

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

运行它时,我从 owners 变量中得到以下错误:

{"Invalid object name 'dbo.Post'."}

我的模型是这些

在所有者数据库中

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

在人物数据库中

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>

我确信这很简单,但我做错了什么以允许它引用所有者的帖子?

最佳答案

给定 s.Postnull,您已禁用 Entity Framework 的延迟加载。要么启用延迟加载,要么显式加载导航属性:

from s in db.Owners.Include(o => o.Post)
orderby s.Post.PostName
...

至于您的编辑,鉴于 Owner.Post 在不同的数据库中,这是一个完全不同的问题。在网上搜索,例如 Cross database querying in EFJoining tables from two databases using entity framework一些提示。在数据库级别链接它们(使用链接服务器或同义词和 View ),或在您的代码中修复它们(循环遍历 Owners 并查找他们的 Post) .

关于c# - 从另一个数据库中的另一个模型引用一个模型asp.net mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32821203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com