简体   繁体   English

如何使用 Net core 3 和 Entity Framework 由新客户端创建新数据库?

[英]How to create new database by new client with Net core 3 and Entity Framework?

I try to use Net core to create an API for a CRM application.The problem is that i don't want to use only one big database for every client of my CRM.我尝试使用 Net core 为 CRM 应用程序创建 API。问题是我不想为我的 CRM 的每个客户只使用一个大数据库。

  • I Have Migration to create the database我有迁移来创建数据库
  • I Have A big ApplicationDBContext and many models我有一个很大的 ApplicationDBContext 和许多模型

What i want is that, for every new client who subscribe, i generate a new database with the name of the company, so the APi use the connectionString with this new database for this new company.我想要的是,对于每个订阅的新客户,我都会生成一个带有公司名称的新数据库,因此 APi 使用这个新公司的连接字符串和这个新数据库。 All Client use the same identity database to subscribe.所有客户端使用相同的身份数据库进行订阅。

Is it possible with EntityFramework and.Net core 3 and how to do that please? EntityFramework 和 .Net core 3 是否有可能,请问如何做到这一点? Thank you:)谢谢:)

Yes, it is possible.对的,这是可能的。 Below, I have created a little sample in.NetCore(3.0) web api.下面,我在.NetCore(3.0) web api 中创建了一个小示例。 The idea is you have to pass a company name in the HttpRequest header and later use it inside your DbContext class.这个想法是您必须在 HttpRequest header 中传递公司名称,然后在您的 DbContext class 中使用它。 In that way you will be able to get an instance of the DbContext with a connectionString that contains the new company name in your controller and create new database with the new company name.通过这种方式,您将能够使用包含 controller 中的新公司名称的 connectionString 获取 DbContext 的实例,并使用新公司名称创建新数据库。

  1. In the appsettings.json create a section called sql that contains a connectionString.在 appsettings.json 中创建一个名为 sql 的部分,其中包含一个连接字符串。 Do not specify a database name and leave it empty after = sign:不要指定数据库名称并在=符号后将其留空:

    "sql": { "connectionString": "Server=localhost;User ID=userId;Password=yourPass;Database=" }

  2. Create a class SqlSettings that will be used to keep the connectionString:创建一个 class SqlSettings用于保持连接字符串:

     public class SqlSettings { public string ConnectionString { get; set; } public void SetDbName(string companyName) { int index = ConnectionString.LastIndexOf("="); if (index > 0) ConnectionString = ConnectionString.Substring(0, index); ConnectionString = $"{ConnectionString}={companyName}"; } }
  3. CustomContext class, it gets the necessary dependencies in its constructor using Dependency Injection and changes the connectionString: CustomContext class,它使用依赖注入在其构造函数中获取必要的依赖关系并更改连接字符串:

     public class CustomContext: DbContext { public string CompanyName { get; private set; } private IOptions<SqlSettings> _sqlSettings; public CustomContext(DbContextOptions<CustomContext> options, IOptions<SqlSettings> sqlSettings, IHttpContextAccessor httpContextAccessor): base(options) { GetDbName(httpContextAccessor.HttpContext.Request); if (string.IsNullOrEmpty(CompanyName)) return; sqlSettings.Value.SetDbName(CompanyName); _sqlSettings = sqlSettings; } private void GetDbName(HttpRequest httpRequest) { try { CompanyName = httpRequest.Headers["CompanyName"]; } catch (Exception) { CompanyName = ""; } } public DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(_sqlSettings.Value.ConnectionString); } }
  4. In our CustomContext class we have a table called Users , It has been created just as a test case:在我们的CustomContext class 中,我们有一个名为Users的表,它被创建为一个测试用例:

     public class User { public Guid Id { get; set; } public string Email { get; set; } public string Password { get; set; } }
  5. Here in Startup.cs class inside the ConfigureServices method we need to register our classes in order to be able to get them using DI.Startup.cs class 的ConfigureServices方法中,我们需要注册我们的类,以便能够使用 DI 获取它们。

     public void ConfigureServices(IServiceCollection services) {...... services.AddHttpContextAccessor(); services.Configure<SqlSettings>(Configuration.GetSection("sql")); services.AddEntityFrameworkSqlServer().AddDbContext<CustomContext>(); }
  6. Now, we can use our CustomContext class inside any Controller , getting it as Action's parameter using Action Method Injection :现在,我们可以在任何Controller中使用我们的CustomContext class ,使用Action Method Injection将其作为Action's参数:

     [HttpGet()] public IActionResult Get([FromServices] CustomContext dbContext) { if (.string.IsNullOrEmpty(dbContext.CompanyName)) dbContext.Database;EnsureCreated(); return Ok(); }

Thus, we can create a new database named as a company name that is extracting from every HttpRequest's header.因此,我们可以创建一个名为公司名称的新数据库,该数据库从每个HttpRequest's header 中提取。 Also, if the database with the same company name already exists, the Entity Framework will not create it again.此外,如果具有相同公司名称的数据库已经存在, Entity Framework将不会再次创建它。

I would do in this way:我会这样做:

create a stored procedure which creates the new database for you, taking as input parameter the new database name and whatever other information is needed for the new client / tenant.创建一个为您创建新数据库的存储过程,将新数据库名称和新客户/租户所需的任何其他信息作为输入参数。

then at the first point when you need to create the new database, you get EF to call that sprocs and database is then created.然后在需要创建新数据库的第一点,让 EF 调用该存储过程,然后创建数据库。

see also here as you are interested in how to do this with a parameter for the new database name:另请参阅此处,因为您对如何使用新数据库名称的参数执行此操作感兴趣:

SQL Server: use parameter in CREATE DATABASE SQL 服务器:在 CREATE DATABASE 中使用参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Entity Framework Core,npgsql,PostgreSQL创建新数据库 - Create new database using Entity Framework Core, npgsql, PostgreSQL 将新表添加到数据库后如何更新 Entity Framework Core - How to update Entity Framework Core after adding a new table to the database 如何使用.NET Standard和Entity Framework Core为现有数据库创建Entity Framework edmx文件? - How to create an Entity Framework edmx file for an existing database with .NET Standard and Entity Framework Core? 如何在命令行上更改连接字符串以在迁移到Entity Framework Core中的新数据库时更新数据库 - How to change connection string on command line to update database on migration to a new database in Entity Framework Core 在 Entity Framework Core 中使用 Update-Database 添加新列 - Adding new column using Update-Database in Entity Framework Core 删除旧的Entity Framework生成的数据库后创建新的数据库 - Create new database after deleting old Entity Framework generated database 使用Entity Framework创建新记录 - Create a new record with Entity Framework 实体框架 6 Create() 与 new - Entity Framework 6 Create() vs new 实体框架代码优先迁移始终尝试创建新数据库 - Entity framework code first migration always tries to create new database 实体框架不会创建新的迁移:数据库名称无效 - Entity Framework does not create a new migration: database name is invalid
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM