在实体框架中添加多对多对象C#
问题描述:
我使用EF和新的它。我有很多很多我的项目在实体框架中添加多对多对象C#
假设我有3个表
- 类:的ClassID,类名
- 学生:StudentID-姓
- StudentClass:StudentID-的ClassID
如果我想将学生添加到我的班级,是否有必要为每个学生传递所有数据?
事情是这样的:
学生表:
StudentID Name
----------------------------
1 Andrew
2 James
类表:
ClassID Name
----------------------------
1 Math
我的代码:
using (var db = factory.CreateContext())
{
Class a = db.Classes.Where(x => x.ClassID == 1)
// Here if I create a `Student`, will it be stored in many to
// many table only passing `StudentID` ?
a.Students.Add(new Student { StudentID = 1 })
a.Students.Add(new Student { StudentID = 2 })
// or do I need do this?
// a.Students.Add(db.Students.where(x=> x.StudentID == 1))?
}
答
如果你已经在数据库中的学生,我强烈建议要做到这一点
// Find the class
Class a = db.Classes.FirtsOrDefault(x => x.ClassID == 1);
// be sure it exists
if(a != null)
{
// find the student
Student s = db.Students.FirtsOrDefault(x => x.StudentID == 1);
// Always check if the object exist on the database,
// the row could be removed from another part of your program.
// Otherwise you will get an error on Add() because object is null
if(s != null)
{
a.Students.Add(s);
}
}
如果您有多个学生加入,你可以搜索那些然后用AddRange
方法。
// find all the student you want (use the search you need)
Student students = db.Students.Where(x => x.StudentID == 1 && x.StudentID == 2 && x.StudentID == 3);
if(students.Count > 0){
a.Students.AddRange(students);
}
+0
检查(object!= null)是否非常重要,如果你不检查这个,你会得到甚至在读取对象的属性时也会出现错误:object.name –
只是创造了'Class'再增加两个新的'Student'实体的Students'的'名单**足以** - 当你存储这个,EF将制定出新产生的所有细节Id的(如果你有'IDENTITY'列)和设置那些在必要的地方,包括“多对多链接”表 –
另外,请参阅[this](https://*.com/documentation/entity-framework/2714/optimize-techniques-in-ef/16628/working-with-stub-entities#t = 201708261958351952897) –