简体   繁体   English

如何使用ASP.NET MVC中的Entity Framework将记录插入到具有外键的表中

[英]How to insert a record into a table with a foreign key using Entity Framework in ASP.NET MVC

I'm new to Entity Framework code-first. 我是Entity Framework代码优先的新手。 This is my learning in ASP.NET MVC, using code-first for database creation. 这是我在ASP.NET MVC中的学习,使用代码优先创建数据库。

I have two classes: 我有两节课:

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public int Standard { get; set; }            
    public int SubjectId { get; set; }    

    [ForeignKey("SubjectId")]
    public ICollection<Subject> Subjects { get; set; }
}

public class Subject
{
    [Key]
    public int SubjectId{ get; set; }
    public string SubjectName { get; set; }
}

I'm trying to insert a Student record into the Student table, which has a foreign key SubjectId referencing the Subject table. 我正在尝试将Student记录插入Student表中,该表具有引用Subject表的外键SubjectId

I'm trying it out in two possible ways: 我正在尝试两种可能的方式:

First approach 第一种方法

using(var cxt = new SchoolContext())
{
    Subject sub = new Subject() { SubjectId = 202, SubjectName ="Geology" };
    Student stu = new Student() { Name = "Riya", SubjectId = 202 };
    cxt.Subjects.Add(sub);
    cxt.Students.Add(stu);           

    cxt.SaveChanges();
}

Here I created a new Subject instance, which has SubjectId=202 . 在这里,我创建了一个新的Subject实例,其SubjectId=202 Now when I create the Student object and assign value 202 to SubjectId , there is an Insert statement conflict. 现在,当我创建Student对象并将值202分配给SubjectId ,存在Insert语句冲突。 Though there is a Subject with SubjectId = 202 , then why is there an insert conflict? 虽然SubjectSubjectId = 202 ,但为什么会出现插入冲突? And when I debug, I see that the navigation property Subjects is null here. 当我调试时,我看到导航属性Subjects在这里为null。 I don't understand the point here. 我不明白这一点。

Second approach: 第二种方法:

using( var cxt=new SchoolContext())
{
    Student stu = new Student() { Name = "Riya" };
    Subject sub = new Subject() { SubjectId = 202, SubjectName = "Geology" };
    stu.Subjects.Add(sub);
    cxt.Students.Add(stu);               

    cxt.SaveChanges();
}

But I get an a null reference exception 但我得到一个空引用异常

Object Reference not set to instance of an Object 对象引用未设置为Object的实例

Why is the stu.Subjects null here? 为什么这里的stu.Subjects null?

So my questions here are: 所以我的问题是:

  1. What does the SubjectId in Student class mean? Student Class中的SubjectId是什么意思? Ie what does its value pertain to? 即它的价值与什么有关? Can we explicitly set it, if yes, will it refer to primary key of Subject table? 我们可以明确设置它,如果是,它会引用Subject表的主键吗? If no, is it specified only for EF code conventions purpose? 如果不是,是否仅为EF代码约定指定了它?

  2. Similarly: what does navigation property role? 同样:导航属性的作用是什么? Why is it null and when it will not be null? 为什么它为null并且何时不为null?

My basic understanding of navigation property is that it is used to make EF determine the relationship between the two entities. 我对导航属性的基本理解是它用于使EF确定两个实体之间的关系。

Can anyone please clarify a bit with examples which would be greatly appreciated. 任何人都可以用一些例子来澄清一下,我们将不胜感激。

You're basically creating a new Student , and a new Subject , in both your approaches. 你基本上都是在你的方法中创建一个新的 Student和一个新的Subject But from what I understand, what you're really trying to do, is create a new Student , and assign an existing Subject (with SubjectId = 202 ) to it - right?? 但根据我的理解,你真正要做的是创建一个新的Student ,并为其分配一个现有的 SubjectSubjectId = 202 ) - 对吗?

The SubjectId in your Student class makes absolutely no sense in this setup - since you have a 1:n relationship between Student and Subject . 您的Student班级中的SubjectId在此设置中完全没有意义 - 因为您在StudentSubject之间有1:n的关系。 You need to use that ICollection<Subject> to handle the 0:n subjects this student is enrolled in. 您需要使用该ICollection<Subject>来处理此学生注册的0:n科目。

For that - use this code: 为此 - 使用此代码:

using(var ctx = new SchoolContext())
{
    // create the *NEW* Student
    Student stu = new Student() { Name = "Riya" };

    // get existing subject with Id=202
    Subject sub = ctx.Subjects.FirstOrDefault(s => s.SubjectId == 202);

    // Add this existing subject to the new student's "Subjects" collection
    stu.Subjects.Add(sub);

    // Add the new student to the context, and save it all.
    ctx.Students.Add(stu);           

    ctx.SaveChanges();
}

That will do - a new student will be inserted into your database table, and the 1:n relationship between student and his subjects will be established. 这样做 - 将新学生插入到您的数据库表中,并建立学生与其科目之间的1:n关系。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.NET MVC中使用实体框架在父表中创建外键并将其分配给子表 - How to create the foreign key in the parent table and assign it to the child table using entity framework in asp.net mvc 我如何在Asp.Net MVC中使用Entity Framework和Web Api获取外键表数据 - How do i get foreign key table data using Entity Framework and Web Api in Asp.Net MVC 没有实体框架外键关系的ASP.NET MVC - Asp.net mvc without entity framework foreign key relationships 使用实体框架使用外键将不同的记录插入表中 - Insert distinct record into table with foreign key using Entity Framework 使用实体框架的代码优先方法在ASP.NET MVC应用程序中缺少外键关系 - Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework 如何使用ASP.NET MVC中该表的另一列获取外键表中的记录ID? - How do I get the id of record in foreign key table using another column in that table in ASP.NET MVC? ASP.NET MVC如何访问Entity Framework生成的外键? - ASP.NET MVC How to access Entity Framework generated foreign key? 如何在 Entity Framework Core 和 ASP.NET Core MVC 中使用外键 - How work with foreign key in Entity Framework Core & ASP.NET Core MVC asp.net mvc-使用实体框架6在第三个表中插入多个具有父级外键的记录 - asp.net mvc - Inserting multiple records in the third table having foreign keys to parent using entity framework 6 INSERT 语句与 FOREIGN KEY SAME TABLE 约束冲突 | ASP.NET Core &amp; Entity Framework Core Code First - The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint | ASP.NET Core & Entity Framework Core Code First
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM