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
.
Looking for your helps.
EDIT
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
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. You can chain the Include directives if you have different referenced objects.
Note : You will have to add :
using Microsoft.EntityFrameworkCore;
on top of your code to allow Include to work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.