0

I have simple repository method in my asp.net core webapi. I am using EF core 2.0. When i update the parent startdate property, i would like to update all the related children to have the same start date. How to achieve this? There is One to Many relation with Course and CourseFormat.

Here is my code snippet:

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;
}
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
  • 3
    related: https://stackoverflow.com/questions/25894587/how-to-update-record-using-entity-framework-6 – xdtTransform Nov 15 '19 at 11:02
  • https://github.com/mono/entityframework/blob/master/src/EntityFramework/Migrations/DbSetMigrationsExtensions.cs#L79 – xdtTransform Nov 15 '19 at 11:02
  • Good comment by xdtTransform! I would also like to see how the Course and CourseFormat objects look – Sandman Nov 15 '19 at 11:06
  • What exactly is the problem? It's not clear if your code does what you expect it to do. – Gert Arnold Nov 15 '19 at 11:17
  • Just make sure `existing.CourseFormat` collection is *loaded* using one of the [Loading Related Data](https://learn.microsoft.com/en-us/ef/core/querying/related-data) methods. Other than that, it's no different than updating the "parent" entity. – Ivan Stoev Nov 15 '19 at 11:29
  • Yeah, but you never tell if it actually works, making it unclear what your'e asking. – Gert Arnold Nov 17 '19 at 21:45

0 Answers0