I am creating a .NET app for school and I am stuck at this strange internal error.
The seed entity for entity type 'ActivityEntity' cannot be added because no value was provided for the required property 'SubjectId'
Here is the ActivityEntity
class:
public record ActivityEntity : IEntity
{
public required DateTime StartDateTime { get; set; }
public required DateTime EndDateTime { get; set; }
public required Room Room { get; set; }
public required ActivityType Type { get; set; }
public string? Description { get; set; }
public required SubjectEntity Subject { get; init; }
public ICollection<EvaluationEntity> Evaluations { get; init; } = new List<EvaluationEntity>();
public required Guid Id { get; set; }
}
And here is the SubjectEntity
:
public record SubjectEntity : IEntity
{
public required string Name { get; set; }
public required string Abbreviation { get; set; }
public ICollection<ActivityEntity> Activities { get; init; } = new List<ActivityEntity>();
public ICollection<StudentEntity> Students { get; init; } = new List<StudentEntity>();
public required Guid Id { get; set; }
}
This is the test that fails:
public async Task AddNew_Activity_Persisted()
{
//Arrange
var entity = ActivitySeeds.ActivityEntity1;
//Act
SISDbContextSUT.Activities.Add(entity);
await SISDbContextSUT.SaveChangesAsync();
//Assert
await using var dbx = await DbContextFactory.CreateDbContextAsync();
var actualEntities = await dbx.Activities.SingleAsync(i => i.Id == entity.Id);
Assert.Equal(entity, actualEntities);
}
This is the part of the code where it fails:
public async Task InitializeAsync()
{
await SISDbContextSUT.Database.EnsureDeletedAsync();
await SISDbContextSUT.Database.EnsureCreatedAsync();
}
I create a new DbContext
and it seems that .NET cannot link the database maybe?
This is the database schema:
Only the Activity and Subject are relevant.
This is how the relationships are defined:
modelBuilder.Entity<StudentEntity>()
.HasMany(i => i.Subjects)
.WithMany(i => i.Students);
modelBuilder.Entity<ActivityEntity>()
.HasOne(i => i.Subject)
.WithMany(i => i.Activities);
modelBuilder.Entity<EvaluationEntity>()
.HasOne(i => i.Activity)
.WithMany(i => i.Evaluations);
modelBuilder.Entity<EvaluationEntity>()
.HasOne(i => i.Student)
.WithMany(i => i.Evaluations);