Entity framework 在数据库中存储值

Entity framework 在数据库中存储值,entity-framework,Entity Framework,我需要在表“StaffSectionInCharge”中添加一些记录,它只有两列StaffId和SectionId,我有StaffId和StudentId的值……问题是我不能直接将记录添加到此表……我使用的是实体框架,此表的设计是 [EdmRelationshipNavigationPropertyAttribute("Model", "StaffSectionInCharge", "Section")] public EntityCollection<Section> Se

我需要在表“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);
            }
        }
    }
我在这里结巴,不能再往前走了,这里有人能帮我吗

你可以试试:

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

staff.Sections.Add(section);

buDataEntities.SaveChanges();
或者(不需要对数据库进行第二次查询):

或者(根本不需要对数据库进行任何查询):


我如何检查正在传递的Id是否已经存在于数据库中……你能帮忙吗me@Shanish:你能把这个问题作为一个新问题问吗?在这里的评论部分更难回答。你能检查这个链接并解决我的问题吗?你能解决这个问题吗。。。。。我认为这是同样的问题,我不知道如何解决这个问题
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();