我有一个问题显示用户的名字(谁创建的公司)在公司的视图列表。
下面是模型“user.cs”的一部分:
using System;
using System.Collections.Generic;
public partial class User
{
public User()
{
// init here
}
// Connections with other Models are here as ICollection
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime Created { get; set; }
}
下面是模型“company.cs”:
using System;
using System.Collections.Generic;
public partial class Company
{
public Company()
{
Accounts = new HashSet<Accounts>();
CompanyHistory= new HashSet<CompanyHistory>();
Earnings= new HashSet<Earnings>();
Expences= new HashSet<Expences>();
}
// other properties those aren't important
public int? UserID { get; set; } // here is User ID
// Other connections those aren't important
public virtual User UserNavigation { get; set; } // Here is connection with Users
}
以下是控制器“CompamyController.cs”的一部分:
public class CompanyController : Controller
{
private readonly MyDBContext _dbContext;
public PoslodavacController(MyDBContext dbContext)
{
_dbContext = dbContext;
}
public IActionResult ViewCompanies()
{
return View(_dbContext.Company);
}
// other code irrelevant for this problem/solution
}
以下是视图“ViewCompanies.cshtml”:
@model IEnumerable<MyDatabase.Models.Company>
@using MyDatabase.Models;
@{
ViewData["Title"] = "ViewCompanies";
Layout = "_Layout";
}
<h1>ViewCompanies</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<!-- other html -->
<th>
<p>User Name</p>
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<!-- Other html data -->
<td>
<!-- ATENTION HERE: @item.KorisnikNavigation is always null so the Name is not retrieved-->
<a asp-route-id="@item.User" asp-controller="User" asp-action="Details">@item.UserNavigation?.Name</a>
</td>
</tr>
}
</tbody>
</table>
我不知道为什么@item.korisniknavigation为空。我是否遗漏了公司构造函数中的某些代码?如果是,什么是必需的代码?
谢谢!
修复操作
public IActionResult ViewCompanies()
{
var model=_dbContext.Set<Company>().Include(i=> i.UserNavigation ).ToArray();
return View(model);
}