我使用EF和新手。我的项目中有很多对
假设我有3个表
如果我想将学生添加到班级,是否需要传递每个学生的所有数据?
这样的事情:
学生表:
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))?
}
答案 0 :(得分: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);
}