I have 2 entities Movie
and MovieVersion
who inherits the following abstract class, defining an ID property:
public interface IEntity
{
int Id { get; }
}
public abstract class EntityBase : IEntity
{
public int Id { get; set; }
}
public class Movie : EntityBase, IAggregateRoot ...
public class MovieVersion : EntityBase ...
I have setup the following configuration:
public class MovieConfiguration : IEntityTypeConfiguration<Movie>
{
public void Configure(EntityTypeBuilder<Movie> builder)
{
builder.HasKey(m => m.Id);
builder.Property(m => m.Id).ValueGeneratedOnAdd();
builder.HasMany(m => m.MovieVersions)
.WithOne();
}
}
public class MovieVersionConfiguration : IEntityTypeConfiguration<MovieVersion>
{
public void Configure(EntityTypeBuilder<MovieVersion> builder)
{
builder.HasKey(m => m.Id);
builder.Property(m => m.Id).ValueGeneratedOnAdd();
}
}
I try to seed with this code:
var movieRepository = new MovieRepository(context);
var movie = new Movie("The Good, the Bad and the Ugly", 1966);
movieRepository.AddMovie(movie);
And I get this error: "Value cannot be null. (Parameter 'key')". What can have gone wrong? I thought that I had it working before, but now something has changed. I'm on EF Core v3.1.1 and using SQLite.
For completeness, here is an excerpt from repository:
public abstract class RepositoryBase<T> where T : class, IAggregateRoot
{
private readonly ApplicationDbContext _context;
public RepositoryBase(ApplicationDbContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
protected DbSet<T> Set => _context.Set<T>();
}
public class MovieRepository : RepositoryBase<Movie>, IMovieRepository
{
public MovieRepository(ApplicationDbContext context) : base(context) {}
public void AddMovie(Movie movie)
{
Set.Add(movie);
}
}
DbContext:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Movie> Movies { get; set; }
public DbSet<MovieVersion> MovieVersions { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
}
}
Seed:
context.Database.EnsureCreated();
if (context.Movies.Any()) return;
var movieRepository = new MovieRepository(context);
var movieContainerRepository = new MovieContainerRepository(context);
var movie = new Movie("The Good, the Bad and the Ugly", 1966);
movieRepository.AddMovie(movie); // throws mentioned error
Thank you in advance!