1视图中的.NET Core EF Core 2模型创建操作 [英] .NET Core EF Core 2 Models in 1 View Create Operation

查看:216
本文介绍了1视图中的.NET Core EF Core 2模型创建操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我读了很多书,但实际上无法弄清楚这应该如何解决. 遵循教程中,我不太清楚如何在正确完成外键映射的情况下一次将数据输入2个模型.

Hi I have read alot but couldn't really figure out how this is suppose to work out. Following this tutorial, I couldn't quite figure out how to input data into 2 models at once with a Foreign Key mapping done properly.

假设我有2个模型(按照本教程进行操作),例如学生和注册,并且我想同时在两个表中输入数据,查看其他堆栈溢出帖子,发现有2种合并方法通过创建大视图"或使用本例中完成的局部视图,将2个视图引入模型.因此,通过将2个对象返回到控制器并将其保存到数据库中(如下所示),它可以工作,除了注册"没有通过StudentID(外键)与Student的任何链接.有没有办法将其设置或绑定在一起?

Supposedly I have to 2 models (following the tutorial), for example student and enrollment and I want to input data to both tables at the same time, looking at other stack overflow posts, I found out that are 2 ways to incorporate 2 views into the model, either by creating a "big view" or using partial view which I have done in this case. So by returning 2 objects to the controller and having it saved to the DB as shown below, it works, except that Enrollment doesn't have any link with Student via studentID (Foreign Key). Is there a way to set it or bind it together?

当前,我可以将两个单独的数据集都保存到数据库中.我似乎无法弄清楚如何设置外键.

Currently I can save both individual set of data to the DB. I just cannot seem to figure out how to set the foreign key.

我现在在2个数据库中拥有的是

What I have now in 2 DBs is

Student      | Enrollment
ID LastName    ID <Some Column> StudentID
1  XXX         1  XXX           NULL (Need this to be 1)

如何获取StudentID为1?

How do I get StudentID to be 1?

public async Task<IActionResult> Create([Bind("ID,LastName")] Student student, [Bind("<Some data inside enrollment>")] Enrollment enrollment)
        {
            if (ModelState.IsValid)
            {
                _context.Add(student);
                await _context.SaveChangesAsync();
                _context.Add(enrollment);
                await _context.SaveChangesAsync();
            return View(student);
        }

非常感谢!非常感谢您的帮助! :)

Thank you very much! Your help is much appreciated! :)

推荐答案

这会有所帮助,

var resultStudent = _context.Add(student);
enrollment.student_id = resultStudent.id;
_context.Add(enrollment);
await _context.SaveChangesAsync();

enrollment.Student = student;
_context.Enrollments.Add(enrollment);
await _context.SaveChangesAsync();

这篇关于1视图中的.NET Core EF Core 2模型创建操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆