I'm just getting started with EF Core (on .NET 8). I have two classes Student
and StudyYear
:
public class Student : Person
{
public int StartYear { get; set; }
public StudyYear StartingStudyYear { get; set; } = new();
public int Class { get; set; }
}
public class StudyYear
{
public int Year { get; set; }
[JsonIgnore]
public ICollection<Student> NewStudents { get; set; } = new HashSet<Student>();
}
I've created a many-to-one relationship:
public static ModelBuilder StudyYear(this ModelBuilder modelBuilder)
{
var entity = modelBuilder.Entity<StudyYear>();
entity.HasKey(sy => sy.Year);
entity
.HasMany(sy => sy.NewStudents)
.WithOne(s => s.StartingStudyYear)
.HasForeignKey(s => s.StartYear)
.IsRequired();
entity.Property(sy => sy.Year).ValueGeneratedNever();
return modelBuilder;
}
When I create the first Student
like this:
var student = new()
{
Class = 1,
StartingStudyYear = new()
{
Year = 2023,
},
}
everything gets created just fine.
The database then looks like this:
Students:
--other data-- | Class | StartYear |
---|---|---|
... | 1 | 2023 |
StudyYears:
Year |
---|
2023 |
But when I add another Student
in 2023, I get this exception:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
MySqlConnector.MySqlException (0x80004005): Duplicate entry '0' for key 'StudyYears.PRIMARY'
I understand that it's trying to add the year 2023 twice like this, but how can I tell it to use the existing one instead of just failing?
I've also tried to load the year from the database if it already exists, like this:
if (context.StudyYears.FirstOrDefault(x => x.Year == model.StartYear)
is not StudyYear startYear)
{
startYear = new StudyYear
{
Year = model.StartYear,
};
}
var entity = context.Add(new Student()
{
StartingStudyYear = startYear,
Class = 1,
});
This does not throw an error anymore, but when I load it from the database now, the StartingStudyYear
is just an empty StudyYear
object.