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