I am writing a simple .NET core library to replicate data from one SQL database to another using EF Core. Rather than replicating the code for each DbSet, I am trying to find a way to create a generic list which I can enumerate and create some logic against.
I have tried to create a Tuple to hold information about the source and destination table, but cannot define a generic DbSet.
I have also create a custom class using generics to set the DbSet type, but cannot add this to a list due to each class type being different.
Example method:
public void Execute()
{
var source = new SourceContext();
var destination = new DestinationContext();
Console.WriteLine("Processing table A");
destination.RemoveRange(destination.TableA);
destination.SaveChanges();
destination.AddRange(source.TableA.AsNoTracking().ToList());
destination.SaveChanges();
}
In order not to replicate the code for additional tables, tried using a Tuple, e.g.
var tables = new List<Tuple<string, DbSet<T>, DbSet<T>>>
{
Tuple.Create("Table A", source.TableA, destination.TableA),
Tuple.Create("Table B", source.TableB, destination.TableB)
};
The problem is defining the Tuple with a generic DbSet, as each item being added has a different type.
Looked at creating a class to define a Table, e.g.
internal class Table<TEntity> where TEntity : class
{
internal string Name {get; set;}
internal DbSet<TEntity> Source {get; set;}
internal DbSet<TEntity> Destination {get; set;}
internal Table(string name, DbSet<TEntity> source, DbSet<TEntity> destination)
{
Name = name;
Source = source;
Destination = destination;
}
}
But then how do I create a List
without a specific type:
var tables = new List<T>
{
new Table<TableA>("Table A", source.TableA, destination.TableA),
new Table<TableB>("Table B", source.TableB, destination.TableB)
};
The List
needs to be instantiated with a type <T>
.
Execute
generic and call it with different types? – DavidG