mohdelle
mohdelle

Reputation: 41

EF Core 6 Navigation Property not updated on database

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;
}

Upvotes: 1

Views: 612

Answers (3)

mohdelle
mohdelle

Reputation: 41

I was looking at wrong place for the bug. Issue is not in the for loop. DB is skipping other records because I have incorrectly set the relationships in Fluent API. Once I got rid of that bug, it's working perfectly. Thank you 🙌

Upvotes: 0

Mih&#225;ly Varga
Mih&#225;ly Varga

Reputation: 1

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();

Upvotes: 0

Diego Lobo
Diego Lobo

Reputation: 466

You can try set the course into TutorialList

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

Upvotes: 2

Related Questions