Adding new DbSet to DbContext when application has started and DbContext created - c#

I have a project, in business it will creates table dynamicaly, its working with netcore3.0 and EF.
When an instance of dbcontext is created after dynamic table is created, I will use Assembly Emit to create a new type of the table, and use OnModelCreating method to add dbsets corresponding to tables.
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public virtual DbSet<Book> Books { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
//Use assmbly emit to create dynamic types
var types = CreateDynamicTypes();
foreach (var type in types)
{
builder.Entity(type);
}
base.OnModelCreating(builder);
}
}
But when a table is created after the dbcontext is created, I dont know how to add new dbset yet, because the OnModelCreating only run 1 time.
The question: How do I add new dbsets to an instance of dbcontext after its created?

OnModelCreating run only 1 time (when it first initialized) because of performance overhead.
There is one way, to bypass this, by using "Model Customizer"
First, you need some tweaking in OnConfiguring (you need to override basic implementation)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
var serviceCollection = new ServiceCollection()
.AddEntityFrameworkSqlServer();
serviceCollection = serviceCollection.AddSingleton<IModelCustomizer, YourModelCustomizer>();
var serviceProvider = serviceCollection.BuildServiceProvider();
optionsBuilder
.UseInternalServiceProvider(serviceProvider);
}
And your Customizer should look like
public class YourModelCustomizer : ModelCustomizer
{
public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
{
base.Customize(modelBuilder, dbContext);
var entityTypeBuilderCart = modelBuilder.Entity<Models.Cart>()
.ToTable("ABC");
entityTypeBuilderCart.Property(a => a.UserId).HasColumnName("XYZ");
entityTypeBuilderCart.Property(a => a.ContractorId).HasColumnName("DFG");
entityTypeBuilderCart.Ignore(a => a.CompanyId);
var entityTypeBuilderCartArticle = modelBuilder.Entity<Models.CartArticle>()
.ToTable("IJK");
entityTypeBuilderCartArticle.Property(a => a.UserId).HasColumnName("QWE");
}
public YourModelCustomizer(ModelCustomizerDependencies dependencies) : base(dependencies)
{
}
}
I hope it will help you.
Be aware that this kind of configuration may cause performance issue.
This code works in EF Core 2.x, in EF 3.x may be some changes, and this code might need some changes.

Related

EF manual/dynamic table registration

I'm trying to create some tables manually and map to DbSet dynamically but it does not work. Here is my DbContext class:
public abstract class DynamicDbContext : DbContext
{
private List<IQueryable> m_dbSets;
public DynamicDbContext([NotNull] DbContextOptions options) :
base(options)
{
}
public DbSet<T> GetTbl<T>() where T : class
{
if (m_dbSets == null)
{
m_dbSets = new List<IQueryable>();
foreach (var iter in GetDynTypes())
{
var setMethod = typeof(DbContext).GetMethod(nameof(DbContext.Set), new[] { typeof(string) });
IQueryable foundSet = (IQueryable)setMethod
.MakeGenericMethod(iter)
.Invoke(this, new object[] { iter.Name });
m_dbSets.Add(foundSet);
}
}
}
return m_dbSets.FirstOrDefault(obj => obj.ElementType == typeof(T)) as DbSet<T>;
}
protected abstract List<Type> GetDynTypes();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var iter in GetDynTypes())
{
EntityTypeBuilder builder = modelBuilder.Entity(iter);
builder.ToTable(iter.Name);
}
}
#endregion
}
The class obtains the dynamic types from application's derived class and should register the classes as tables to database. Then I would like to use Linq to work with the tables, so I introduced GetTbl method which would return the DbSet<T> so the application can call Linq on this set. This method use reflection to obtain the DbSet, but I also tried directly call Set<T>(typeof(T).Name).
When I try to access the returned DbSet the result is exception:
Cannot create a DbSet for 'Abc' because this type is not included in the model for the context
It looks like the table(s) are created e.g. when I run migration command I can see the tables in the database:
dotnet ef migrations add InitialCreate
The problem is probably with the table mapping to DbSet - in my GetTbl method. Or maybe I need to do something extra in OnModelCreating method.
Not sure what is the problem. Any help is appreciated :-)
Thanks
Once you register the types in OnModelCreating, you can get the DbSet's with simply
myDbContext.Set<T>();
And so a simpler design is to just use a single generic type that you specialize at runtime with the dynamic entity type. eg
public class DynamicDbContext<T> : DbContext where T:class
{
public DynamicDbContext([NotNull] DbContextOptions options) :
base(options)
{
}
public DbSet<T> Entities => this.Set<T>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<T>().ToTable(typeof(T).Name);
base.OnModelCreating(modelBuilder);
}
}
Of course this won't create the table if it doesn't exist.

Create one lazy and one eager DbContext via inheritance?

I am using EFCore 3.1.5 and I have a DbContext I want to be able to use in the same controller or service either lazy or eager. However, it seems like I cannot get it to load lazy properly. Eager seems to work fine.
Whenever I do something as simple as:
var users = await _lazyDbContext
.Users
.Take(10)
.ToListAsync();
each navigational property on each User is null. However, with eager loading, it works fine:
var users = await _dbContext
.Users
.Include(x => x.Contact)
.Take(10)
.ToListAsync();
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<LazyUserContext>((sp, opt) =>
{
var connectionString = "very secret";
opt.UseSqlServer(connectionString, x => x.CommandTimeout(300));
opt.UseLazyLoadingProxies();
});
services.AddDbContext<UserContext>((sp, opt) =>
{
var connectionString = "very secret";
opt.UseSqlServer(connectionString, x => x.CommandTimeout(300));
});
services.AddScoped<IUserContext, UserContext>();
services.AddScoped<ILazyUserContext, LazyUserContext>();
}
UserContext.cs
public interface IUserContext
{
DbSet<User> Users { get; set; }
DbSet<Contact> Contacts { get; set; }
}
public class UserContext : DbContext, IUserContext
{
public UserContext(DbContextOptions<UserContext> options) : base(options) {}
public DbSet<User> Users { get; set; }
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Users>(e =>
{
e.HasOne(x => x.Contact).WithOne(x => x.User).HasForeignKey(x => x.ContactId);
}
}
}
LazyUserContext.cs
public interface ILazyUserContext : IContext {}
public class LazyUserContext : UserContext, ILazyUserContext
{
public LazyUserContext(DbContextOptions<UserContext> options) : base(options) {}
}
What could the issue be here? I have tried to IoC both the interface and the class in my controller/service. I have tried with and without the services.AddScoped<>().
All I want is be able to use a lazy dbContext or eager dbContext, where I want to default to the eager one.
The solution
All I want is be able to use a lazy dbContext or eager dbContext
You should be able to just set the configuration in the subclasses:
public class LazyContext : MyContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLazyLoadingProxies();
}
}
public class EagerContext : MyContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
}
There are two options of setting db option configuration, via the the constructor (and thus the DI route), or via the class itself. Since this particular setting is class-specific and you don't want to juggle it in the DI registration, it makes sense to rely on the class-specific configuration method.
Why your solution didn't work
The reason your initial approach didn't work is because AddDbContext<T> registers that specific T as your dependency type. From the source:
The AddDbContext extension method registers DbContext types with a scoped lifetime by default.
Note that it registers the context type, not any interfaces/ancestors of that context type.
So when you do this:
services.AddDbContext<LazyUserContext>((sp, opt) =>
{
var connectionString = "very secret";
opt.UseSqlServer(connectionString, x => x.CommandTimeout(300));
opt.UseLazyLoadingProxies();
});
services.AddScoped<ILazyUserContext, LazyUserContext>();
If your class has a dependency of type ILazyUserContext, it only listens to the second registration and flatout ignores the first one.
Only when your class has a dependency of LazyUserContext will you actually get the db context options you specified in the first registration.
Note that you can use this type-specific registration behavior to your advantage when you want to register a default implementation:
// Specific interface => specific type
services.AddScoped<IUserContext, UserContext>();
services.AddScoped<ILazyUserContext, LazyUserContext>();
// General interface => explicitly chosen default type
services.AddScoped<IContext, UserContext>();
This allows you to have some classes that demand to specifically have the eager/lazy loading, and other classes which just take in whatever is the default (which could change over time).
The problem is caused by the fact that both context constructors use (depend on) one and the same options type - DbContextOptions<UserContext>.
AddDbContext<TContext> actually registers two types - the context itself TContext as well as factory for the context options dependency DbContextOptions<TContext>.
So you are registering two options factories (along with configuration action) - DbContextOptions<UserContext> and DbContextOptions<LazyUserContext>. However, as mentioned at the beginning LazyUserContext depends on DbContextOptions<UserContext>, so it's simply instantiated with the first options set-up, i.e. exactly like the other.
This is not specific for lazy loading, but for any scenario which requires different options (different database type/connection string etc.) and is the reason generic class DbContextOptions<TContext> exists.
The solution is to change the LazyUserContext dependency
public LazyUserContext(DbContextOptions<LazyUserContext> options) : base(options) { }
and since this won't compile because the base expects DbContextOptions<UserContext>, add second protected constructor to the base class accepting just DbContextOptions
protected UserContext(DbContextOptions options) : base(options) { }

EF Core HasQueryFilter works for only the first value in filter expression

I am using EF Core HasQueryFilter extension method, which is inside the OnModelCreating method.
I am injecting the user id into the DbContext using a service and then applying the userId to the query filter. For the first time when the OnModelCreating is executed it works fine as expected. But when I change the user and pass a different userId to the DbContext then query filter is not affected as obvious because the OnModelCreating is not called this time.
A little background of the App: It's a core 2.2 API project which authenticates users using the JWT token. I populate the user claims and initialize the injected auth service using the JWT, so for every call to the API the userId can be different hence query filter should work on different userIds.
Example codes below:
public class SqlContext : DbContext
{
private readonly IAuthService _authService;
public SqlContext(DbContextOptions options, IAuthService authService) : base(options)
{
_authService = authService;
}
public DbSet<Device> Devices { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Device>().HasQueryFilter(p => !p.IsDeleted && p.ManufacturerId == _authService.ManufacturerId);
}
}
How the DbContext is initialized.
services.AddDbContextPool<TContext>(o =>
o.UseSqlServer(configuration["Settings:SqlServer:DefaultConnection"],
b =>
{
b.MigrationsAssembly(configuration["Settings:SqlServer:MigrationAssembly"]);
b.CommandTimeout(60);
b.EnableRetryOnFailure(2);
})
.ConfigureWarnings(warnings =>
{
warnings.Throw(RelationalEventId.QueryClientEvaluationWarning);
}))
.AddTransient<TContext>();
Finally solved it.
As the filter was working, but it was not getting updated once the model was created after first request. The reason was that EF was caching the created model. So, I had to implement the IModelCacheKeyFactory in order to capture the different models as per the filters.
internal class DynamicModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
{
if (context is SqlContext dynamicContext)
{
return (context.GetType(), dynamicContext._roleCategory);
}
return context.GetType();
}
}
And attached it to the context like this.
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
base.OnConfiguring(builder);
builder.ReplaceService<IModelCacheKeyFactory, DynamicModelCacheKeyFactory>();
}

How to use IdentityDbContext

For the last few days, I have been playing around with Asp.net's Identity framework.
I have been able to get the Register and Login working however when I try to extend the functionality to saving data against specific users, I find it is different to how I would normally implement it with stock standard EF.
Normally I would use something like below to save data:
using(var context = myDbContex())
{
context.Add(object);
context.SaveChanges();
}
However, when I try to use this approach after inheriting the IdentityDbContext it is expecting an argument. Is it okay for me to create a default constructor that doesn't take any arguments or should I be passing something in?
My Context currently looks like this:
public class AppContext : IdentityDbContext<ApplicationUser>
{
//I am not really sure why options needs to be specified as an argument
public AppContext(DbContextOptions<AppContext> options)
: base(options)
{
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<Xxxxx> Xxxxx { get; set; }
public DbSet<Yyyyy> Yyyyy { get; set; }
public DbSet<Zzzzz> Zzzzz { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppContext>(options =>
options.UseSqlite("Data Source=App.db"));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AppContext>()
.AddDefaultTokenProviders();
});
Why is this implementation of the context different to the standard dbContext, and how can I save data using this context?
Thanks
Because of this line
services.AddDbContext<AppContext>(options => options.UseSqlite("DataSource=App.db"));
You need to provide a constructor that has the DbContextOptions as paramter, which has nothing todo with IdentityDbContext.
You have two choices now.
Use dependency injection, that is how you are supposed to use it anyway
public class MyController : Controller
{
private AppContext context;
public MyController(AppContext context)
{
this.context = context;
}
}
Secondly you could register your context differently.
services.AddDbContext<AppContext>();
And apply changes in your context, remove the constructor and override OnConfiguring(DbContextOptionsBuilder optionsBuilder)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=App.db");
}
Now you can use it as you usually would do.
using(var context = new AppContext())
{
// do stuff
}
EDIT:
Not part of the actual question but signin, registration and role managing is handled by these classes, that can be injected when using IdentityDbContext
SignInManager
UserManager
RoleManager

Dynamically changing schema in Entity Framework Core

UPD here is the way I solved the problem. Although it's likely to be not the best one, it worked for me.
I have an issue with working with EF Core. I want to separate data for different companies in my project's database via schema-mechanism. My question is how I can change the schema name in runtime? I've found similar question about this issue but it's still unanswered and I have some different conditions. So I have the Resolve method that grants the db-context when necessary
public static void Resolve(IServiceCollection services) {
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<DomainDbContext>()
.AddDefaultTokenProviders();
services.AddTransient<IOrderProvider, OrderProvider>();
...
}
I can set the schema-name in OnModelCreating, but, as was found before, this method is called just once, so I can set schema name globaly like that
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
}
or right in the model via an attribute
[Table("order", Schema = "public")]
public class Order{...}
But how can I change the schema name on runtime? I create the context per each request, but first I fugure out the schema-name of the user via a request to a schema-shared table in the database. So what is the right way to organize that mechanism:
Figure out the schema name by the user credentials;
Get user-specific data from database from specific schema.
Thank you.
P.S. I use PostgreSql and this is the reason for lowecased table names.
Did you already use EntityTypeConfiguration in EF6?
I think the solution would be use mapping for entities on OnModelCreating method in DbContext class, something like this:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
using Microsoft.Extensions.Options;
namespace AdventureWorksAPI.Models
{
public class AdventureWorksDbContext : Microsoft.EntityFrameworkCore.DbContext
{
public AdventureWorksDbContext(IOptions<AppSettings> appSettings)
{
ConnectionString = appSettings.Value.ConnectionString;
}
public String ConnectionString { get; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConnectionString);
// this block forces map method invoke for each instance
var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet());
OnModelCreating(builder);
optionsBuilder.UseModel(builder.Model);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.MapProduct();
base.OnModelCreating(modelBuilder);
}
}
}
The code on OnConfiguring method forces the execution of MapProduct on each instance creation for DbContext class.
Definition of MapProduct method:
using System;
using Microsoft.EntityFrameworkCore;
namespace AdventureWorksAPI.Models
{
public static class ProductMap
{
public static ModelBuilder MapProduct(this ModelBuilder modelBuilder, String schema)
{
var entity = modelBuilder.Entity<Product>();
entity.ToTable("Product", schema);
entity.HasKey(p => new { p.ProductID });
entity.Property(p => p.ProductID).UseSqlServerIdentityColumn();
return modelBuilder;
}
}
}
As you can see above, there is a line to set schema and name for table, you can send schema name for one constructor in DbContext or something like that.
Please don't use magic strings, you can create a class with all available schemas, for example:
using System;
public class Schemas
{
public const String HumanResources = "HumanResources";
public const String Production = "Production";
public const String Sales = "Sales";
}
For create your DbContext with specific schema you can write this:
var humanResourcesDbContext = new AdventureWorksDbContext(Schemas.HumanResources);
var productionDbContext = new AdventureWorksDbContext(Schemas.Production);
Obviously you should to set schema name according schema's name parameter's value:
entity.ToTable("Product", schemaName);
Define your context and pass the schema to the constructor.
In OnModelCreating Set the default schema.
public class MyContext : DbContext , IDbContextSchema
{
private readonly string _connectionString;
public string Schema {get;}
public MyContext(string connectionString, string schema)
{
_connectionString = connectionString;
Schema = schema;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.ReplaceService<IModelCacheKeyFactory, DbSchemaAwareModelCacheKeyFactory>();
optionsBuilder.UseSqlServer(_connectionString);
}
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(Schema);
// ... model definition ...
}
}
Implement your IModelCacheKeyFactory.
public class DbSchemaAwareModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
{
return new {
Type = context.GetType(),
Schema = context is IDbContextSchema schema
? schema.Schema
: null
};
}
}
In OnConfiguring replace the default implementation of IModelCacheKeyFactory with your custom implementation.
With the default implementation of IModelCacheKeyFactory the method OnModelCreating is executed only the first time the context is instantiated and then the result is cached.
Changing the implementation you can modify how the result of OnModelCreating is cached and retrieve. Including the schema in the caching key you can get the OnModelCreating executed and cached for every different schema string passed to the context constructor.
// Get a context referring SCHEMA1
var context1 = new MyContext(connectionString, "SCHEMA1");
// Get another context referring SCHEMA2
var context2 = new MyContext(connectionString, "SCHEMA2");
Sorry everybody, I should've posted my solution before, but for some reason I didn't, so here it is.
BUT
Keep in mind that anything could be wrong with the solution since it neither hasn't been reviewed by anybody nor production-proved, probably I'll get some feedback here.
In the project I used ASP .NET Core 1
About my db structure. I have 2 contexts. The first one contains information about users (including the db scheme they should address), the second one contains user-specific data.
In Startup.cs I add both contexts
public void ConfigureServices(IServiceCollection
services.AddEntityFrameworkNpgsql()
.AddDbContext<SharedDbContext>(options =>
options.UseNpgsql(Configuration["MasterConnection"]))
.AddDbContext<DomainDbContext>((serviceProvider, options) =>
options.UseNpgsql(Configuration["MasterConnection"])
.UseInternalServiceProvider(serviceProvider));
...
services.Replace(ServiceDescriptor.Singleton<IModelCacheKeyFactory, MultiTenantModelCacheKeyFactory>());
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Notice UseInternalServiceProvider part, it was suggested by Nero Sule with the following explanation
At the very end of EFC 1 release cycle, the EF team decided to remove EF's services from the default service collection (AddEntityFramework().AddDbContext()), which means that the services are resolved using EF's own service provider rather than the application service provider.
To force EF to use your application's service provider instead, you need to first add EF's services together with the data provider to your service collection, and then configure DBContext to use internal service provider
Now we need MultiTenantModelCacheKeyFactory
public class MultiTenantModelCacheKeyFactory : ModelCacheKeyFactory {
private string _schemaName;
public override object Create(DbContext context) {
var dataContext = context as DomainDbContext;
if(dataContext != null) {
_schemaName = dataContext.SchemaName;
}
return new MultiTenantModelCacheKey(_schemaName, context);
}
}
where DomainDbContext is the context with user-specific data
public class MultiTenantModelCacheKey : ModelCacheKey {
private readonly string _schemaName;
public MultiTenantModelCacheKey(string schemaName, DbContext context) : base(context) {
_schemaName = schemaName;
}
public override int GetHashCode() {
return _schemaName.GetHashCode();
}
}
Also we have to slightly change the context itself to make it schema-aware:
public class DomainDbContext : IdentityDbContext<ApplicationUser> {
public readonly string SchemaName;
public DbSet<Foo> Foos{ get; set; }
public DomainDbContext(ICompanyProvider companyProvider, DbContextOptions<DomainDbContext> options)
: base(options) {
SchemaName = companyProvider.GetSchemaName();
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasDefaultSchema(SchemaName);
base.OnModelCreating(modelBuilder);
}
}
and the shared context is strictly bound to shared schema:
public class SharedDbContext : IdentityDbContext<ApplicationUser> {
private const string SharedSchemaName = "shared";
public DbSet<Foo> Foos{ get; set; }
public SharedDbContext(DbContextOptions<SharedDbContext> options)
: base(options) {}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasDefaultSchema(SharedSchemaName);
base.OnModelCreating(modelBuilder);
}
}
ICompanyProvider is responsible for getting users schema name. And yes, I know how far from the perfect code it is.
public interface ICompanyProvider {
string GetSchemaName();
}
public class CompanyProvider : ICompanyProvider {
private readonly SharedDbContext _context;
private readonly IHttpContextAccessor _accesor;
private readonly UserManager<ApplicationUser> _userManager;
public CompanyProvider(SharedDbContext context, IHttpContextAccessor accesor, UserManager<ApplicationUser> userManager) {
_context = context;
_accesor = accesor;
_userManager = userManager;
}
public string GetSchemaName() {
Task<ApplicationUser> getUserTask = null;
Task.Run(() => {
getUserTask = _userManager.GetUserAsync(_accesor.HttpContext?.User);
}).Wait();
var user = getUserTask.Result;
if(user == null) {
return "shared";
}
return _context.Companies.Single(c => c.Id == user.CompanyId).SchemaName;
}
}
And if I haven't missed anything, that's it. Now in every request by an authenticated user the proper context will be used.
I hope it helps.
There are a couple ways to do this:
Build the model externally and pass it in via DbContextOptionsBuilder.UseModel()
Replace the IModelCacheKeyFactory service with one that takes the schema into account
Took several hours to figure this out with EFCore. Seems to be alot of confusion on the proper way of implementing this. I believe the simple and correct way of handling custom models in EFCore is replacing the default IModelCacheKeyFactory service like I show below. In my example I am setting custom table names.
Create a ModelCacheKey variable in your context class.
In your context constructor, set the ModelCacheKey variable
Create a class that inherits from IModelCacheKeyFactory and use ModelCacheKey (MyModelCacheKeyFactory)
In OnConfiguring method (MyContext), replace the default IModelCacheKeyFactory
In OnModelCreating method (MyContext), use the ModelBuilder to define whatever you need.
public class MyModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
=> context is MyContext myContext ?
(context.GetType(), myContext.ModelCacheKey) :
(object)context.GetType();
}
public partial class MyContext : DbContext
{
public string Company { get; }
public string ModelCacheKey { get; }
public MyContext(string connectionString, string company) : base(connectionString)
{
Company = company;
ModelCacheKey = company; //the identifier for the model this instance will use
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//This will create one model cache per key
optionsBuilder.ReplaceService<IModelCacheKeyFactory, MyModelCacheKeyFactory();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
//regular entity mapping
});
SetCustomConfigurations(modelBuilder);
}
public void SetCustomConfigurations(ModelBuilder modelBuilder)
{
//Here you will set the schema.
//In my example I am setting custom table name Order_CompanyX
var entityType = typeof(Order);
var tableName = entityType.Name + "_" + this.Company;
var mutableEntityType = modelBuilder.Model.GetOrAddEntityType(entityType);
mutableEntityType.RemoveAnnotation("Relational:TableName");
mutableEntityType.AddAnnotation("Relational:TableName", tableName);
}
}
The result is each instance of your context will cause efcore to cache based on the ModelCacheKey variable.
I find this blog might be useful for you. Perfect !:)
https://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/
This blog is based on ef4, I'm not sure whether it will work fine with ef core.
public class ContactContext : DbContext
{
private ContactContext(DbConnection connection, DbCompiledModel model)
: base(connection, model, contextOwnsConnection: false)
{ }
public DbSet<Person> People { get; set; }
public DbSet<ContactInfo> ContactInfo { get; set; }
private static ConcurrentDictionary<Tuple<string, string>, DbCompiledModel> modelCache
= new ConcurrentDictionary<Tuple<string, string>, DbCompiledModel>();
/// <summary>
/// Creates a context that will access the specified tenant
/// </summary>
public static ContactContext Create(string tenantSchema, DbConnection connection)
{
var compiledModel = modelCache.GetOrAdd(
Tuple.Create(connection.ConnectionString, tenantSchema),
t =>
{
var builder = new DbModelBuilder();
builder.Conventions.Remove<IncludeMetadataConvention>();
builder.Entity<Person>().ToTable("Person", tenantSchema);
builder.Entity<ContactInfo>().ToTable("ContactInfo", tenantSchema);
var model = builder.Build(connection);
return model.Compile();
});
return new ContactContext(connection, compiledModel);
}
/// <summary>
/// Creates the database and/or tables for a new tenant
/// </summary>
public static void ProvisionTenant(string tenantSchema, DbConnection connection)
{
using (var ctx = Create(tenantSchema, connection))
{
if (!ctx.Database.Exists())
{
ctx.Database.Create();
}
else
{
var createScript = ((IObjectContextAdapter)ctx).ObjectContext.CreateDatabaseScript();
ctx.Database.ExecuteSqlCommand(createScript);
}
}
}
}
The main idea of these codes is to provide a static method to create different DbContext by different schema and cache them with certain identifiers.
You can use Table attribute on the fixed schema tables.
You can't use attribute on schema changing tables and you need to configure that via ToTable fluent API.
If you disable the model cache (or you write your own cache), the schema can change on every request so on the context creation (every time) you can to specify the schema.
This is the base idea
class MyContext : DbContext
{
public string Schema { get; private set; }
public MyContext(string schema) : base()
{
}
// Your DbSets here
DbSet<Emp> Emps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Emp>()
.ToTable("Emps", Schema);
}
}
Now, you can have some different ways to determine the schema name before creating the context.
For example you can have your "system tables" on a different context so on every request you retrieve the schema name from the user name using the system tables and than create the working context on the right schema (you can share tables between contexts).
You can have your system tables detached from the context and use ADO .Net to access to them.
Probably there are several other solutions.
You can also have a look here
Multi-Tenant With Code First EF6
and you can google ef multi tenant
EDIT
There is also the problem of the model caching (I forgot about that).
You have to disable the model caching or change the behavior of the cache.
maybe I'm a bit late to this answer
my problem was handling different schema with the same structure lets say multi-tenant.
When I tried to create different instances of the same context for the different schemas, Entity frameworks 6 comes to play, catching the first time the dbContext was created then for the following instances they were creates with a different schemas name but onModelCreating were never called meaning that each instance was pointing to the same previously catched Pre-Generated Views, pointing to the first schema.
Then I realized that creating new classes inheriting from myDBContext one for each schema will solve my problem by overcoming entity Framework catching problem creating one new fresh context for each schema, but then comes the problem that we will end with hardcoded schemas, causing another problem in terms of code scalability when we need to add another schema, having to add more classes and recompile and publish a new version of the application.
So I decided to go a little further creating, compiling and adding the classes to the current solution in runtime.
Here is the code
public static MyBaseContext CreateContext(string schema)
{
MyBaseContext instance = null;
try
{
string code = $#"
namespace MyNamespace
{{
using System.Collections.Generic;
using System.Data.Entity;
public partial class {schema}Context : MyBaseContext
{{
public {schema}Context(string SCHEMA) : base(SCHEMA)
{{
}}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{{
base.OnModelCreating(modelBuilder);
}}
}}
}}
";
CompilerParameters dynamicParams = new CompilerParameters();
Assembly currentAssembly = Assembly.GetExecutingAssembly();
dynamicParams.ReferencedAssemblies.Add(currentAssembly.Location); // Reference the current assembly from within dynamic one
// Dependent Assemblies of the above will also be needed
dynamicParams.ReferencedAssemblies.AddRange(
(from holdAssembly in currentAssembly.GetReferencedAssemblies()
select Assembly.ReflectionOnlyLoad(holdAssembly.FullName).Location).ToArray());
// Everything below here is unchanged from the previous
CodeDomProvider dynamicLoad = CodeDomProvider.CreateProvider("C#");
CompilerResults dynamicResults = dynamicLoad.CompileAssemblyFromSource(dynamicParams, code);
if (!dynamicResults.Errors.HasErrors)
{
Type myDynamicType = dynamicResults.CompiledAssembly.GetType($"MyNamespace.{schema}Context");
Object[] args = { schema };
instance = (MyBaseContext)Activator.CreateInstance(myDynamicType, args);
}
else
{
Console.WriteLine("Failed to load dynamic assembly" + dynamicResults.Errors[0].ErrorText);
}
}
catch (Exception ex)
{
string message = ex.Message;
}
return instance;
}
I hope this help someone to save some time.
Update for MVC Core 2.1
You can create a model from a database with multiple schemas. The system is a bit schema-agnostic in its naming. Same named tables get a "1" appended. "dbo" is the assumed schema so you don't add anything by prefixing a table name with it the PM command
You will have to rename model file names and class names yourself.
In the PM console
Scaffold-DbContext "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force -Tables TableA, Schema1.TableA
I actually found it to be a simpler solution with an EF interceptor.
I actually keep the onModeling method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("dbo"); // this is important to always be dbo
// ... model definition ...
}
And this code will be in Startup:
public void ConfigureServices(IServiceCollection services)
{
// if I add a service I can have the lambda (factory method) to read from request the schema (I put it in a cookie)
services.AddScoped<ISchemeInterceptor, SchemeInterceptor>(provider =>
{
var context = provider.GetService<IHttpContextAccessor>().HttpContext;
var scheme = "dbo";
if (context.Request.Cookies["schema"] != null)
{
scheme = context.Request.Cookies["schema"];
}
return new SchemeInterceptor(scheme);
});
services.AddDbContext<MyContext>(options =>
{
var sp = services.BuildServiceProvider();
var interceptor = sp.GetService<ISchemeInterceptor>();
options.UseSqlServer(Configuration.GetConnectionString("Default"))
.AddInterceptors(interceptor);
});
And the interceptor code looks something like this (but basically we use ReplaceSchema):
public interface ISchemeInterceptor : IDbCommandInterceptor
{
}
public class SchemeInterceptor : DbCommandInterceptor, ISchemeInterceptor
{
private readonly string _schema;
public SchemeInterceptor(string schema)
{
_schema = schema;
}
public override Task<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<object> result,
CancellationToken cancellationToken = new CancellationToken())
{
ReplaceSchema(command);
return base.ScalarExecutingAsync(command, eventData, result, cancellationToken);
}
public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<object> result)
{
ReplaceSchema(command);
return base.ScalarExecuting(command, eventData, result);
}
public override Task<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<int> result,
CancellationToken cancellationToken = new CancellationToken())
{
ReplaceSchema(command);
return base.NonQueryExecutingAsync(command, eventData, result, cancellationToken);
}
public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
{
ReplaceSchema(command);
return base.NonQueryExecuting(command, eventData, result);
}
public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
ReplaceSchema(command);
return result;
}
public override Task<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = new CancellationToken())
{
ReplaceSchema(command);
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
}
private void ReplaceSchema(DbCommand command)
{
command.CommandText = command.CommandText.Replace("[dbo]", $"[{_schema}]");
}
public override void CommandFailed(DbCommand command, CommandErrorEventData eventData)
{
// here you can handle cases like schema not found
base.CommandFailed(command, eventData);
}
public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData,
CancellationToken cancellationToken = new CancellationToken())
{
// here you can handle cases like schema not found
return base.CommandFailedAsync(command, eventData, cancellationToken);
}
}
If the only difference between databases is schema name the simplest way to get rid of the problem is to remove line of code which is setting the default schema in OnModelCreating method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
modelBuilder.HasDefaultSchema("YourSchemaName"); <-- remove or comment this line
...
}
In this case underneeth sql queries run by EF Core won't contain schema name in their FROM clause. Then you will be able to write a method which will set correct DbContext depending on your custom conditions.
Here is an example which I used to connect to different Oracle databases with the same database structure (in short let's say that in Oracle schema is the same as user). If you're using another DB you just need to put correct connection string and then modify it.
private YourDbContext SetDbContext()
{
string connStr = #"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=server_ip)(PORT=1521)))(CONNECT_DATA=(SID = server_sid)));User Id=server_user ;Password=server_password";
//You can get db connection details e.g. from app config
List<string> connections = config.GetSection("DbConneections");
string serverIp;
string dbSid;
string dBUser;
string dbPassword;
/* some logic to choose a connection from config and set up string variables for a connection*/
connStr = connStr.Replace("server_ip", serverIp);
connStr = connStr.Replace("server_sid", dbSid);
connStr = connStr.Replace("server_user", dBUser);
connStr = connStr.Replace("server_password", dbPassword);
var dbContext = dbContextFactory.CreateDbContext();
dbContext.Database.CloseConnection();
dbContext.Database.SetConnectionString(connStr);
return dbContext;
}
Finally you will be able to set desired dbContext where it's needed invoking this method before, you can also pass some arguments to the method to help you choose correct db.

Categories

Resources