1

我需要从表“StaffSectionInCharge”中获取所有 Id,它只有两列 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);
            }
        }
    }

我可以通过人员表访问此表,例如

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 表中......

这里我想获取对应SectionId的所有StaffId

我试着变得喜欢

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

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

            }

但它不起作用,任何人都可以在这里帮助我

4

1 回答 1

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();

两种选择都应该有效。如果SectionId是您的主键,Section您可以将第二个代码简化为:

var staffIds = buDataEntities.Sections
    .Where(se => se.SectionId == SectionId)
    .Select(se => se.Staffs.Select(st => st.StaffId))
    .SingleOrDefault();
于 2012-04-17T12:40:28.843 回答