【发布时间】:2021-04-08 14:53:05
【问题描述】:
我在查看公司列表中显示用户名(创建公司的人)时遇到问题。
这是模型“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 为空。 我错过了 Company 构造函数中的一些代码吗?如果有,需要的代码是什么?
谢谢!
【问题讨论】:
标签: c# entity-framework asp.net-core .net-core entity-framework-core