2012-04-17 119 views
1

我需要從表「StaffSectionInCharge」中獲取所有Ids',它只有兩列StaffId和SectionId,我有StaffId和StudentId的值.....問題是我不能直接將記錄到該表.....我使用實體框架,該表的設計是使用foreach獲取Sql表中的所有值

[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); 
      } 
     } 
    } 

我可以通過員工表訪問此表像

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

staff.Sections.Add(section); 
buDataEntities.savechanges(); 

這樣我可以添加記錄到這個StaffSectionInCharge表....

在這裏,我想所有的StaffIds爲相應SectionId

我試圖讓喜歡

DataAccess.Staff staffs = new DataAccess.Staff(); 

foreach (int staff in staffs.Sections.Select(s=>s.SectionId)) 
      { 

      } 

,但其沒有工作,任何人都可以幫助我在這裏

回答

1
var staffIds = buDataEntities.Staffs 
    .Where(st => st.Sections.Any(se => se.SectionId == SectionId)) 
    .Select(st => st.StaffId) 
    .ToList(); 

var staffIds = buDataEntities.Sections 
    .Where(se => se.SectionId == SectionId) 
    .SelectMany(se => se.Staffs.Select(st => st.StaffId)) 
    .Distinct() 
    .ToList(); 

兩種選擇守則ld工作。如果SectionIdSection主鍵,你可以smplify第二代碼:

var staffIds = buDataEntities.Sections 
    .Where(se => se.SectionId == SectionId) 
    .Select(se => se.Staffs.Select(st => st.StaffId)) 
    .SingleOrDefault(); 
+0

感謝alotttttttttt Slauma – shanish 2012-04-17 12:56:56

+0

u能幫助我在這裏也http://stackoverflow.com/q/10187231/1239554 – shanish 2012-04-17 12:57:33

+0

Slauma,u能幫我在這裏http://stackoverflow.com/questions/10910370/get-values-from-foreign-key-table – shanish 2012-06-06 11:47:25