EntityFramework and SQL Server Remove Related Entity

Viewed 260

I am having a weird issue with my understanding of Entity Framework.

I have the following sample objects recording as data in my SQL Database.

public class Competition 
{
    public long Id { get; set;}
    public string Name { get; set; }
}

public class SeasonCompetition 
{
    public long Id { get; set;}
    public string Name { get; set; }
    public Competition Competition { get; set; }
}

Now, I create a new instance of Competition and save it to the database. I then create a new instance of SeasonCompetition relating to the created Competition.

Competition competition = new Competition();
competition.Name = "Test";
_context.Add(competition);
_context.SaveChanges();

SeasonCompetition seasoncompetition = new SeasonCompetition();
seasoncompetition.Name = "Test Season Comp";
seasoncompetition.Competiton = competition;
_context.Add(seasoncompetition);
_context.SaveChanges();

This successfully writes a record to the SeasonCompetitions table looking a bit like this.

Id Name SeasonCompetitionId
1 Test Season Competition 1

Now, I want to remove the relationship so this SeasonCompetition does not relate to the Competition record

seasoncompetition.Competition = null;
_context.Update(seasoncompetition);
_context.SaveChanges();

If I put a breakpoint in and examine the seasoncompetition object after SaveChanges(), I can see seasoncompetition.Competition = null, but looking at the database, it still shows this.

Id Name SeasonCompetitionId
1 Test Season Competition 1

How do I update the SeasonCompetition record to remove the relationship to Competition but still keep the Competition record in place in the database?

Using Visual Studio 2022 and .NET 5

2 Answers

Using Microsoft.EntityFrameworkCore - make 'Competition' nullable:

public class SeasonCompetition
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Competition? Competition { get; set; }
}

Calling _context.Update(seasoncompetition) doesn't do anything in this case. This is how you should do it:

        //create
        var competition = new Competition
        {
            Name = $"Competition {DateTime.Now.Millisecond}"
        };
        _context.Competitions.Add(competition);
        _context.SaveChanges();

        var season = new SeasonCompetition
        {
            Competition = competition,
            Name = $"Season {DateTime.Now.Millisecond}"
        };
        _context.SeasonCompetitions.Add(season);
        _context.SaveChanges();

        //Created season & competition

        season.Competition = null;
        _context.SaveChanges();

        //Removed competition from season

This feature is called change tracking whereby the data context automatically can detect when a model has changed if it is associated to the data context. You can read more about this here: https://docs.microsoft.com/en-us/ef/core/change-tracking/

Related