2017-08-16 112 views
0

我使用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))? 
} 
+0

只是創造了'Class'再增加兩個新的'Student'實體的Students'的'名單**足以** - 當你存儲這個,EF將制定出新產生的所有細節Id的(如果你有'IDENTITY'列)和設置那些在必要的地方,包括「多對多鏈接」表 –

+0

另外,請參閱[this](https://stackoverflow.com/documentation/entity-framework/2714/optimize-techniques-in-ef/16628/working-with-stub-entities#t = 201708261958351952897) –

回答

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 –