.NET CORE , EntityFrameworkCore
DbContext
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// LIKE THIS
// dynamically
Map(); // of Entity method (any Entity what i need)
// INSTEAD OF
modelBuilder.Entity<Message>(opt =>
{
opt.ToTable("Message");
opt.HasKey(x => x.Id);
opt.Property(x => x.AutoId).UseSqlServerIdentityColumn();
opt.HasAlternateKey(x => x.AutoId);
});
modelBuilder.Entity<User>(opt =>
{
opt.ToTable("User");
opt.HasKey(x => x.Id);
opt.Property(x => x.AutoId).UseSqlServerIdentityColumn();
opt.HasAlternateKey(x => x.AutoId);
});
// x100 Entity more maybe ??
}
}
.
Base of Entities
public abstract interface IEntity
{
abstract void Map(ModelBuilder modelBuilder);
}
public abstract class BaseEntity : IEntity
{
public abstract void Map(ModelBuilder modelBuilder);
}
I have some Entities :
public class Message : BaseEntity
{
public string Content { get; set; }
public Guid FromUserId { get; set; }
public Guid ToUserId { get; set; }
[ForeignKey("FromUserId")]
public virtual User FromUser { get; set; }
[ForeignKey("ToUserId")]
public virtual User ToUser { get; set; }
public override void Map(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Message>(opt =>
{
opt.ToTable("Message");
opt.HasKey(x => x.Id);
opt.Property(x => x.AutoId).UseSqlServerIdentityColumn();
opt.HasAlternateKey(x => x.AutoId);
});
}
}
.
public class User : BaseEntity
{
public virtual List<Message> ReceivedMessages { get; set; }
public virtual List<Message> SentMessages { get; set; }
public override void Map(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(opt =>
{
opt.ToTable("User");
opt.HasKey(x => x.Id);
opt.Property(x => x.AutoId).UseSqlServerIdentityColumn();
opt.HasAlternateKey(x => x.AutoId);
});
}
}
How to map an entity's Map method to DataContext's OnModelCreating dynamically.
I use Unit Of Work Design Pattern. I'm creating dbSet to get table's data like this :
private readonly DbContext _dbContext;
//
dbContext.Set<T>(); // T is BaseEntity
When i run Set method dbContext, dbContext's OnModelCreating method is firing.
How can i do ?

BaseEntity? - pokeSet<T>(), theOnModelCreatingwill already have fired; in fact, it needs to run pretty early in the database context construction, and I don’t think you can add things to it later. – What is wrong with the database context knowing beforehand which entity types it supports? - poke