2012-03-29 116 views
0

我需要在表中添加一些記錄「StaffSectionInCharge」,它只有兩列StaffId和SectionId,我有值的StaffId和StudentId .....問題是我無法添加直接記錄到該表.....我使用實體框架,該表的設計是存儲在數據庫中的值

[EdmRelationshipNavigationPropertyAttribute("Model", "StaffSectionInCharge", "Section")] 
    public EntityCollection<Section> Sections 
    { 
     get 
     { 
      return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Section>("Model.StaffSectionInCharge", "Section"); 
     } 
     set 
     { 
      if ((value != null)) 
      { 
       ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Section>("Model.StaffSectionInCharge", "Section", value); 
      } 
     } 
    } 

我需要通過員工表來訪問此表,我試圖像

DataAccess.Staff staff = buDataEntities.Staffs.First(s=>s.StaffId==StaffId); 
       staff.Sections.Add(); 

上午stucking在這裏,不能進一步移動,任何人都可以幫助我在這裏

回答

1

你可以試試:

Staff staff = buDataEntities.Staffs.First(s => s.StaffId == StaffId); 
Section section = buDataEntities.Sections.First(s => s.SectionId == SectionId); 

staff.Sections.Add(section); 

buDataEntities.SaveChanges(); 

或(這並不需要第二個數據庫查詢):

Staff staff = buDataEntities.Staffs.First(s => s.StaffId == StaffId); 

Section section = new Section { SectionId = SectionId }; 
buDataEntities.Sections.Attach(section); 

staff.Sections.Add(section); 

buDataEntities.SaveChanges(); 

或(它不需要任何數據庫查詢所有):

Staff staff = new Staff { StaffId = StaffId }; 
buDataEntities.Staffs.Attach(staff); 

Section section = new Section { SectionId = SectionId }; 
buDataEntities.Sections.Attach(section); 

staff.Sections.Add(section); 

buDataEntities.SaveChanges(); 
+0

很大,其工作...........感謝alottt – shanish 2012-03-29 17:45:32

+0

我怎麼能檢查哪些想過去的ID是否已經存在於數據庫...... u能幫我 – shanish 2012-04-04 04:16:14

+0

@Shanish:你可以問這個問題嗎?在評論部分回答更加困難。 – Slauma 2012-04-04 09:43:08