I'm trying to create a dynamic MySQL "EntityFramework Core" connection object, that is responsible for connection junction tables.
This is my interface for specifying a junction table:
public interface IJunctionTable<T1,T2>
{
int ID { get; set; }
int CompositeKeyA { get; set; }
int CompositeKeyB { get; set; }
T1 DataModelRelationA { get; set; }
T2 DataModelRelationB { get; set; }
}
This is my interface for specifying that a table has a relation to a junction table:
public interface IJunctionRelationModel<TJunctionTable> where TJunctionTable : class, new()
{
ICollection<TJunctionTable> NavigationCollection { get; set; }
}
Here is the code I want to change so that it's able to fit all junction tables. This code works but is hard coded to use table "MediaDataModel" and "PerformerDataModel". Is it posible to change this architecture to something dynamically ?
public class MySQLJunctionConnection<T> : DbContext where T : class, IJunctionTable<MediaDataModel, PerformerDataModel>
{
public DbSet<T> DataModel { get; private set; }
public DbContextOptionsBuilder Connection { get; private set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
this.Connection = optionsBuilder;
this.Connection.UseMySql(@"server=mysqlexample.com;database=mydatabase;uid=user1;password=mypassword;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<T>().HasKey(pk => new { pk.CompositeKeyA, pk.CompositeKeyB });
modelBuilder.Entity<T>().HasOne(a => a.DataModelRelationA).WithMany(a => (IEnumerable<T>)a.NavigationCollection).OnDelete(DeleteBehavior.Cascade).HasForeignKey(m => m.CompositeKeyA);
modelBuilder.Entity<T>().HasOne(mp => mp.DataModelRelationB).WithMany(p => (IEnumerable<T>)p.NavigationCollection).OnDelete(DeleteBehavior.Cascade).HasForeignKey(p => p.CompositeKeyB);
}
}
What I have tried:
I've tried alot of different things.
I've tried making the tables generic T1 and T2, but then the modelBuilder complaines that it is an interface and not a reference type.