UPD here是解决问题的方法。虽然它可能不是最好的,但它对我有用。
我在使用EF Core时遇到问题。我想通过模式机制将项目数据库中不同公司的数据分开。我的问题是如何在运行时更改模式名称?我发现similar question关于这个问题,但它仍然是答案,我有一些不同的条件。所以我有Resolve
方法在必要时授予db-context
public static void Resolve(IServiceCollection services) {
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<DomainDbContext>()
.AddDefaultTokenProviders();
services.AddTransient<IOrderProvider, OrderProvider>();
...
}
我可以在OnModelCreating
中设置schema-name,但是,如前所述,这个方法只调用一次,所以我可以像这样设置模式名称globaly
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
}
或在模型中通过类似
的属性[Table("order", Schema = "public")]
public class Order{...}
但是如何在运行时更改模式名称?我根据每个请求创建了ef的上下文,但首先我通过请求为数据库中的某个模式共享表格查找了用户的模式名称。那么组织该机制的真正方法是什么:
谢谢。
P.S。我使用PostgreSql,这是表名低的原因。
答案 0 :(得分:9)
您是否已在EF6中使用EntityTypeConfiguration?
我认为解决方案是在DbContext类中使用OnModelCreating方法上的实体映射,如下所示:
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);
}
}
}
OnConfiguring方法上的代码强制在DbContext类的每个实例创建时执行MapProduct。
MapProduct方法的定义:
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;
}
}
}
正如您在上面所看到的,有一行为表设置模式和名称,您可以在DbContext中为一个构造函数发送模式名称或类似的东西。
请不要使用魔术字符串,您可以创建一个包含所有可用模式的类,例如:
using System;
public class Schemas
{
public const String HumanResources = "HumanResources";
public const String Production = "Production";
public const String Sales = "Production";
}
要创建具有特定架构的DbContext,您可以写下:
var humanResourcesDbContext = new AdventureWorksDbContext(Schemas.HumanResources);
var productionDbContext = new AdventureWorksDbContext(Schemas.Production);
显然你应该根据模式名称参数的值来设置模式名称:
entity.ToTable("Product", schemaName);
答案 1 :(得分:4)
有几种方法可以做到这一点:
DbContextOptionsBuilder.UseModel()
IModelCacheKeyFactory
服务替换为考虑模式的服务答案 2 :(得分:3)
我发现此博客可能对您有用。完美!:)
https://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/
此博客基于ef4,我不确定它是否可以与ef核心一起使用。
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);
}
}
}
}
这些代码的主要思想是提供一种静态方法,通过不同的模式创建不同的DbContext,并使用某些标识符缓存它们。
答案 3 :(得分:3)
对不起每个人,我之前应该发布我的解决方案,但由于某种原因我没有,所以现在就是。
<强> BUT 强>
请记住,解决方案可能有任何问题,因为它既没有经过任何人审核也没有经过生产证明,可能我会在这里得到一些反馈。
在项目中我使用了ASP .NET Core 1
关于我的数据库结构。我有2个背景。第一个包含有关用户的信息(包括他们应该解决的数据库方案),第二个包含用户特定的数据。
在Startup.cs
我添加两个上下文
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>();
注意UseInternalServiceProvider
部分,Nero Sule建议使用以下说明
在EFC 1发布周期的最后,EF团队决定从默认服务集合中删除EF的服务(AddEntityFramework()。AddDbContext()),这意味着使用EF自己的服务提供商解决服务而不是应用程序服务提供商。
要强制EF使用您的应用程序的服务提供程序,您需要先将EF的服务与数据提供程序一起添加到服务集合中,然后配置DBContext以使用内部服务提供程序
现在我们需要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);
}
}
其中DomainDbContext
是具有用户特定数据的上下文
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();
}
}
此外,我们必须稍微更改上下文本身以使其具有架构感知功能:
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);
}
}
并且共享上下文严格绑定到shared
架构:
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
负责获取用户架构名称。是的,我知道它与完美的代码有多远。
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;
}
}
如果我没有错过任何东西,那就是它。现在,在经过身份验证的用户的每个请求中,都将使用正确的上下文。
我希望它有所帮助。
答案 4 :(得分:2)
也许我对这个答案有点晚了
我的问题是处理具有相同结构的不同架构,比如说多租户。
当我尝试为不同的架构创建相同上下文的不同实例时,实体框架6开始发挥作用,捕捉到第一次创建dbContext的情况,然后为以下实例创建了具有不同架构名称的实例,但是onModelCreating从未调用表示每个实例都指向相同的先前捕获的“预生成视图”,并指向第一个架构。
然后,我意识到为每个模式创建一个从myDBContext继承的新类将通过克服实体框架来解决我的问题,该框架捕获为每个模式创建一个新的新上下文的问题,但是随之而来的问题是,我们将以硬编码模式结束,从而导致在代码可伸缩性方面,当我们需要添加另一个架构,必须添加更多的类并重新编译并发布新版本的应用程序时,这是另一个问题。
因此,我决定在运行时进一步创建,编译类并将其添加到当前解决方案中。
这是代码
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;
}
我希望这可以帮助某人节省一些时间。
答案 5 :(得分:2)
花几个小时用EFCore来解决这个问题。似乎对实现此方法的正确方法感到困惑。我相信在EFCore中处理自定义模型的简单正确的方法是替换默认的IModelCacheKeyFactory服务,如下所示。在我的示例中,我正在设置自定义表名称。
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);
}
}
结果是您上下文的每个实例都会导致efcore基于ModelCacheKey变量进行缓存。
答案 6 :(得分:1)
您可以在固定架构表上使用Table属性。
您无法在架构更改表上使用属性,您需要通过ToTable fluent API进行配置 如果禁用模型缓存(或者编写自己的缓存),则模式可以在每个请求上更改,因此在创建上下文时(每次)都可以指定模式。
这是基本想法
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);
}
}
现在,在创建上下文之前,您可以使用一些不同的方法来确定模式名称
例如,您可以在不同的上下文中使用“系统表”,以便在每次请求时使用系统表从用户名中检索模式名称,然后在正确的模式上创建工作上下文(您可以在上下文之间共享表)。
您可以将系统表与上下文分离,并使用ADO .Net访问它们
可能还有其他一些解决方案。
你也可以看看这里 Multi-Tenant With Code First EF6
你可以谷歌ef multi tenant
修改强>
还存在模型缓存的问题(我忘记了)。
您必须禁用模型缓存或更改缓存的行为。
答案 7 :(得分:1)
定义您的contex并将架构传递给构造函数。
在OnModelCreating中设置默认架构
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 ...
}
}
实现您的IModelCacheKeyFactory。
public class DbSchemaAwareModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
{
return new {
Type = context.GetType(),
Schema = context is IDbContextSchema schema
? schema.Schema
: null
};
}
}
用On替换用自定义实现配置IModelCacheKeyFactory的默认实现。
使用IModelCacheKeyFactory的默认实现,仅在第一次实例化上下文然后缓存结果时才执行OnModelCreating方法。 更改实现,您可以修改OnModelCreating结果的缓存和检索方式。将方案包含在缓存键中,您可以为传递给上下文构造函数的每个不同的方案字符串执行和缓存OnModelCreating。
// Get a context referring SCHEMA1
var context1 = new MyContext(connectionString, "SCHEMA1");
// Get another context referring SCHEMA2
var context2 = new MyContext(connectionString, "SCHEMA2");
答案 8 :(得分:0)
MVC Core 2.1的更新
您可以从具有多个架构的数据库中创建模型。该系统的命名方式与模式无关。相同名称的表将附加“ 1”。 “ dbo”是假定的架构,因此您无需通过在表名前添加PM命令来添加任何内容
您将必须自己重命名模型文件名和类名。
在PM控制台中
Scaffold-DbContext "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force -Tables TableA, Schema1.TableA
答案 9 :(得分:0)
我实际上发现它是使用EF拦截器的简单解决方案。
我实际上保留了onModeling方法:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("dbo"); // this is important to always be dbo
// ... model definition ...
}
此代码将在“启动”中:
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);
});
拦截器代码如下所示(但基本上我们使用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);
}
}
答案 10 :(得分:0)
如果数据库之间的唯一区别是模式名称,那么摆脱问题的最简单方法是删除在 OnModelCreating 方法中设置默认模式的代码行:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
modelBuilder.HasDefaultSchema("YourSchemaName"); <-- remove or comment this line
...
}
在这种情况下,EF Core 运行的 sql 查询将不会在它们的 FROM 子句中包含架构名称。然后您将能够编写一个方法,该方法将根据您的自定义条件设置正确的 DbContext。 这是我用来连接到具有相同数据库结构的不同 Oracle 数据库的示例(简而言之,假设在 Oracle 模式中与用户相同)。如果您使用另一个数据库,您只需要输入正确的连接字符串然后修改它。
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;
}
最后,您将能够在需要调用此方法的地方设置所需的 dbContext,您还可以向该方法传递一些参数以帮助您选择正确的 db。