EntityFramework如何在更新父项时更新所有子项属性

时间:2019-11-15 10:58:16

标签: c# entity-framework-core

我的asp.net核心webapi中有简单的存储库方法。我正在使用EF core 2.0。当我更新父项startdate属性时,我想将所有相关的子项更新为具有相同的开始日期。如何实现呢?与Course和CourseFormat有一对多的关系。

这是我的代码段:

public Course SaveCourse(Course item)            
{
    if (item.CourseId == 0)
        _context.Course.Add(item);
    else
    {
        var existing = _context.Course.SingleOrDefault(course => course.CourseId == item.CourseId);
        existing.CourseCode = item.CourseCode;
        existing.CourseName = item.CourseName;
        existing.Purpose = item.Purpose;
        existing.CourseDescription = item.CourseDescription;
        existing.AutomaticNotifications = item.AutomaticNotifications;
        existing.StartDate = item.StartDate;
        existing.EndDate = item.EndDate;
        existing.ModifiedBy = item.ModifiedBy;
        existing.Modified = item.Modified;
**// trying the following. is this right?**
        foreach(var courseFormat in existing.CourseFormat)
            courseFormat.StartYear = existing.StartDate.Value.Year;
        item.CreatedBy = existing.CreatedBy;
        item.Created = existing.Created;
    }

    _context.SaveChanges();
    return item;
}

0 个答案:

没有答案