[英]How to retrieve data of nested class instance from parent class instance in ASP.NET Core?
I am trying to modeling a class at school, and I end up with something like this: 我试图在学校模拟一个班级,结果却是这样的:
public class Class
{
public int ID { get; set; }
public int Grade { get; set; }
public Teacher ClassTeacher { get; set; }
}
This is the Teacher class: 这是教师班:
public class Teacher
{
public int ID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
public DateTime Birthday { get; set; }
}
When I use scaffolding, migrate and update the database, this is the structure Entity Framework built for me: 当我使用脚手架,迁移和更新数据库时,这是为我构建的实体框架结构:
dbo.Class:
ID: int
ClassTeacherID: int
Grade: int
dbo.Teacher:
ID: int
Birthday: datetime2(7)
FirstName: nvarchar(MAX)
LastName: nvarchar(MAX)
I want to display the Teacher
's FirstName
in Views\\Classes\\Details.cshtml
, but the Model.ClassTeacher
is null
, even after I created a Teacher
instance in the database and set ClassTeacherID
to the newly created Teacher
's ID
. 我想在Views\\Classes\\Details.cshtml
显示Teacher
的FirstName
,但是即使在数据库中创建了Teacher
实例并将ClassTeacherID
设置为新创建的Teacher
ID
之后, Model.ClassTeacher
还是为null
。
Looking for your helps. 寻找您的帮助。
EDIT 编辑
ClassesController.cs ClassesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Models
{
public class ClassesController : Controller
{
private readonly WebApplication1Context _context;
public ClassesController(WebApplication1Context context)
{
_context = context;
}
// GET: Classes
public async Task<IActionResult> Index()
{
return View(await _context.Class.ToListAsync());
}
// GET: Classes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var @class = await _context.Class
.SingleOrDefaultAsync(m => m.ID == id);
if (@class == null)
{
return NotFound();
}
return View(@class);
}
// GET: Classes/Create
public IActionResult Create()
{
return View();
}
// POST: Classes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,Grade")] Class @class)
{
if (ModelState.IsValid)
{
_context.Add(@class);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(@class);
}
// GET: Classes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var @class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
if (@class == null)
{
return NotFound();
}
return View(@class);
}
// POST: Classes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Grade")] Class @class)
{
if (id != @class.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(@class);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClassExists(@class.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(@class);
}
// GET: Classes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var @class = await _context.Class
.SingleOrDefaultAsync(m => m.ID == id);
if (@class == null)
{
return NotFound();
}
return View(@class);
}
// POST: Classes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var @class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
_context.Class.Remove(@class);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool ClassExists(int id)
{
return _context.Class.Any(e => e.ID == id);
}
}
}
TeachersController.cs TeachersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Models
{
public class TeachersController : Controller
{
private readonly WebApplication1Context _context;
public TeachersController(WebApplication1Context context)
{
_context = context;
}
// GET: Teachers
public async Task<IActionResult> Index()
{
return View(await _context.Teacher.ToListAsync());
}
// GET: Teachers/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher
.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// GET: Teachers/Create
public IActionResult Create()
{
return View();
}
// POST: Teachers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
{
if (ModelState.IsValid)
{
_context.Add(teacher);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(teacher);
}
// GET: Teachers/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// POST: Teachers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
{
if (id != teacher.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(teacher);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TeacherExists(teacher.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(teacher);
}
// GET: Teachers/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher
.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// POST: Teachers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
_context.Teacher.Remove(teacher);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool TeacherExists(int id)
{
return _context.Teacher.Any(e => e.ID == id);
}
}
}
I know it's been a while since the question has been written, but you should try to Include the object reference you want. 我知道问题已经写了一段时间了,但是您应该尝试包括所需的对象引用。
var @class = await _context.Class.Include("Teacher")
.SingleOrDefaultAsync(m => m.ID == id);
Include will get the dependent object and put it back in your Class model. Include将获取依赖对象,并将其放回您的Class模型中。 You can chain the Include directives if you have different referenced objects. 如果您有不同的引用对象,则可以链接Include指令。
Note : You will have to add : 注意:您必须添加:
using Microsoft.EntityFrameworkCore;
on top of your code to allow Include to work. 在您的代码之上以允许“包含”起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.