Home > front end >  EF Core 6 Navigation Property not updated on database
EF Core 6 Navigation Property not updated on database

Time:02-05

My Models (changed for brevity):

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Tutorial>? Tutorials { get; set; }
}

public class Tutorial
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int CourseId { get; set; }
    public Course Course { get; set; }
}

Im trying to persist a course which consists a list of tutorials on sqlite db. Here's a simple version of my code.

// create a new Course with user input name
// get list of tutorials by looping through data from external api
course.Tutorials = tutorialsAppendedInsideForLoop();
context.Courses.Add(course);
await context.SaveChangesAsync();

My Course item was saved on db. But surprisingly only the last item in my Tutorials list got persisted. Not the whole list.

Im struggling to find the issue here.

UPDATE:

Here is the forloop code:

private List<Tutorial> TutorialsAppendedInsideForLoop(Course course)
{
    var tuts = CallToExternalApi();

    var tutorials = new List<Tutorial>();

    for (int i = 0; i < tuts.Count; i  )
    {
        var tutorial = new Tutorial
        {
            Title = tuts[i].Name,
            Course = course
        };

        tutorials.Add(tutorial);                        
    }

    return tutorials;
}

CodePudding user response:

You can try set the course into TutorialList

foreach(var tutorial in tutorials)
{
    tutorial.Course = course;
    ...
}

CodePudding user response:

Add the courses inside the foreach:

var course = context.Courses.Where(x => x.Id == id);

            foreach (var tutorial in tutorials)
            {
                course.Tutorials.Add(tutorial);
            }

            context.SaveChangesAsync();
  •  Tags:  
  • Related