rgvlee/EntityFrameworkCore.Testing

DBContext with two sets of the same type throws an exception

Closed this issue · 4 comments

In: https://github.com/rgvlee/EntityFrameworkCore.Testing/blob/96f430239787c694e06f957b159b175ffcc8a0d6/src/EntityFrameworkCore.Testing.Moq/Helpers/NoSetUpDefaultValueProvider.cs

SetUpReadOnlyModel()

This line:

        var property = typeof(TDbContext).GetProperties().SingleOrDefault(p => p.PropertyType == typeof(DbSet<TEntity>));

leads to an exception if the dbcontext has two sets of the same type. In my case I have two sets going against different views that return the same data (in my case, active and retired workers).

Can you share

  • The EntityFrameworkCore.Testing.Moq and EFCore versions you are using
  • A DbContext with model configuration for the given scenario (doesn't need to be your actual implementation, something representative of the scenario is fine)

EntityFrameworkCore.Testing.Moq - 3.0.2
MOQ - 4.16.1
Can't see an obvious way to get EFCore version

This DB Context (with unrelated bits removed) caused the error:

` public class ImaNuclearOdsContext : DbContext
{
public ImaNuclearOdsContext(DbContextOptions options) : base(options) { }

    public virtual DbSet<Worker> Worker { get; set; } = default!;
    public virtual DbSet<Worker> WorkerRetired { get; set; } = default!;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Worker>().HasNoKey().ToView("Worker_Info_Active_Employee_Contractor", "Workforce");
        modelBuilder.Entity<Worker>().HasNoKey().ToView("Worker_Info", "Workforce");
    }
}

`

Changing the line to:

    public virtual DbSet<RetiredWorker> WorkerRetired { get; set; } = default!;

resolved the issue, but now I have to do with object mapping I wouldn't need to do normally.

Thanks!

Interesting case. My first thought would be what does

var workers = context.Set<Worker>().ToList()

return? The rows in Worker_Info_Active_Employee_Contractor or Worker_Info?

Can't say I've attempted this before.

What's the behaviour when tested against an SQL Server database?

  • Do the views map to the Worker and WorkerRetired properties as expected?
    • If so, I can only assume this works on property definition order, doesn't sound great!
  • What view is Set<Worker>() mapped to?

Have you got a link which describes this behaviour?

When pressed... I think this is user error on my part!

This stack overflow reiterates your point: https://stackoverflow.com/questions/38640279/how-to-create-2-dbsets-with-the-same-type-in-entity-framework-code-first

I'm gonna close this out as your plugin was correctly pointing out I was doing something foolish.