'C# Lambda expression using dynamic type

I'm trying to create a copy of every entity that is a subclass of BaseEntity. I'm using the repository pattern to access the database, and my idea is to get a repository for each type, get the entities and add them back with different values. I have the following code in a .NET 6 application:

Startup.cs

services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

BaseEntity.cs

public class BaseEntity {
    public int Id { get; set; }
    public int BaseId { get; set; }
}

ChildEntity.cs

public class ChildEntity : BaseEntity { ... }

MyController.cs

var childClasses = Assembly.GetAssembly(typeof(BaseEntity))!.GetTypes()
    .Where(type => type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(BaseEntity)))
    .ToList();

foreach (var type in childClasses)
{
    Type repositoryType = typeof(IRepository<>);
    Type constructed = repositoryType.MakeGenericType(type);
    dynamic repository = _serviceProvider.GetService(constructed)!;
    var entities = repository.Set().Where(e => e.BaseId == 0).ToList();
    
    foreach (var entity in entities)
    {
        entity.Id = 0;
        entity.BaseId = newBaseId;
        repository.Set().Add(entity);
    }

    await repository.GetContext().SaveChangesAsync(cancellationToken);
}

But the entities line gives the error: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

I understand that this is a limitation of using dynamic, but is there any way around it? The only solution I came up with was enumerating the whole Set() and using a foreach + if.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source