shanish
shanish

Reputation: 1984

storing values in database

I need to add some records in the table "StaffSectionInCharge", it has only two columns StaffId and SectionId, I have values of StaffId and StudentId.....the problem is I can't add the records directly to this table.....am using entity framework and the design of this table is

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

I need to access this table through Staff table, I tried like

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

am stucking here, and cant move further, can anyone help me here

Upvotes: 0

Views: 51

Answers (1)

Slauma
Slauma

Reputation: 177133

You can try:

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

staff.Sections.Add(section);

buDataEntities.SaveChanges();

Or (which doesn't need the second query to the database):

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

Or (which doesn't need any query to the database at all):

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

Upvotes: 1

Related Questions