更新记录时将记录添加到联结表

时间:2016-08-04 21:46:35

标签: entity-framework

我有一个Designs表,链接到一个链接到DesignAnalysisSoftware查找表的联结表。它是1对多对1的关系。我试图找到一种更新记录并添加/删除联结表中任何记录而不触及查找表的方法。我找到了一种从联结表中删除记录的方法,但是在更新刚插入联结表的父记录时无法找到方法。

我使用的代码如下。

public bool UpdateDesign(Design design){
            if (!Validate(design)){
                return false;
            }

            var DesignFromDb = _context.Designs.Single(d => d.StructureId == design.StructureId);

            if (DesignFromDb != null){
                _context.Entry(DesignFromDb).CurrentValues.SetValues(design);

                DesignFromDb.ModifiedDate = DateTime.Now;
                DesignFromDb.ModifiedByFullName = base.GetUsersFullName();
                DesignFromDb.ModifiedBy = base.GetUserLogin();

                DesignFromDb.DesignAnalysisSoftwares.Clear();
                DesignFromDb.DesignAnalysisSoftwares = design.DesignAnalysisSoftwares; <- this adds to the junction table but also adds to the lookup table

                }
            }

1 个答案:

答案 0 :(得分:0)

如果design.DesignAnalysisSoftwares;设置了PK值,则只需将design.DesignAnalysisSoftwares;的状态更改为EntityState.Unchanged,如this answer中所述:

if (design.DesignAnalysisSoftwares != null)
{
    foreach (var designSoft in design.DesignAnalysisSoftwares)
        _context.Entry(designSoft).State = EntityState.Unchanged;
}