【问题标题】:storing values in database在数据库中存储值
【发布时间】:2012-03-29 13:07:47
【问题描述】:

我需要在“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 表访问这个表,我试过了

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

卡在这里,不能再往前走,谁能帮帮我

【问题讨论】:

    标签: entity-framework


    【解决方案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();
    

    【讨论】:

    • 如何检查正在传递的ID是否已经存在于数据库中......你能帮帮我吗
    • @Shanish:你能问这个问题吗?在评论部分这里更难回答。
    • 你可以检查这个链接并解决我的问题stackoverflow.com/q/10189850/1239554
    • 你能解决这个问题吗?Slauma stackoverflow.com/q/10211705/1239554.....我认为它是同样的问题,我不知道如何解决这个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    相关资源
    最近更新 更多