将值存储在数据库中

时间:2012-03-29 13:07:48

标签: entity-framework

我需要在表“StaffSectionInCharge”中添加一些记录,它只有两列StaffId和SectionId,我有StaffId和StudentId的值......问题是我无法直接将记录添加到此table ..... am使用实体框架,这个表的设计是

[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表访问此表,我试过

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

我在这里,并且无法继续前进,任何人都可以帮助我

1 个答案:

答案 0 :(得分: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();