简体   繁体   English

如何从ASP.NET Core中的父类实例检索嵌套类实例的数据?

[英]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显示TeacherFirstName ,但是即使在数据库中创建了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.

相关问题 如何从Asp.net核心依赖注入中注册的子类解析父类实例 - How to resolve parent class instance from registered child class in Asp.net core dependency injection 将 class 实例关联到 asp.net 内核中的 Session - Associate class instance to Session in asp.net core asp.net核心-在应用启动后创建类的实例 - asp.net core - create an instance of a class after the app started Asp.Net Core - 访问 IStringLocalizer 实例形式 static class - Asp.Net Core - Access IStringLocalizer instance form static class 如何在ASP.NET缓存中存储类实例(帮助程序类)? - How to store class instance (helper class) in ASP.NET Cache? 有没有办法从 ASP.NET Core IFileProvider 类中检索 HttpContext? - Is there a way to retrieve HttpContext from ASP.NET Core IFileProvider class? 如何在asp.net中仅创建一次类的实例 - How to create instance of a class only once in asp.net ASP.NET Core创建类可以在其中使用DI的类实例-寻找模式建议 - ASP.NET Core Create class instance where class may use DI - looking for pattern advice 如何从类的实例访问嵌套类? - How to access nested class from instance of a class? ASP.NET Core DI不同的选项实例取决于请求的类 - ASP.NET Core DI different options instance depending on requesting class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM