DotNetCore cross-platform ~ How to create the EFCore data context, dotnetcoreefcore
Back to directory
For DotNetCore, most components are placed in the DI container, injected in startup, and used in the class constructor. In some cases, this DI method cannot be used, you can also control the data context production process by yourself.
1. Use of standard injection + Constructor
The definition of the data context and the Construction Method with parameters. Note that it has nothing to do with the type of database to be used. It is just a simple context.
public partial class ErpContext : DbContext, IERPContext { public ErpContext(DbContextOptions dbContextOptions) : base(dbContextOptions) { } }
Inject the specified data source and database connection string in the startup class. Note that the database type (such as sqlserver, mysql, and sqllite) and data connection string are available here.
services.AddDbContextPool<ErpContext>( options => options.UseMySql("Server=123.56.31.133;DataBase=erp;UID=front;Password=PlP2017_#Test;charset=utf8;port=3306;SslMode=None"));
For the user, it is implemented on a controller through the DI of the constructor. In fact, dotnetcore integrates the ioc & di modes.
public ValuesController(ErpContext context) { this.context = context; }
2. directly create the data context and manually create the DbContextOptions object without using injection.
Similar to the traditional method, a connection string is fixed in the data context object, that is, a context only belongs to a database!
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql("Server=123.56.31.133;DataBase=erp;UID=front;Password=PlP2017_#Test;charset=utf8;port=3306;SslMode=None"); base.OnConfiguring(optionsBuilder); }
Third, use injection and automatic construction to establish data context.
In fact, optionsBuilder is passed in as a parameter during context initialization, which is flexible.
public class ERPRepository<T> : EFRepository<T> where T : class { public ERPRepository() : base(new ErpContext( new DbContextOptionsBuilder().UseMySql("Server=123.56.31.133;DataBase=erp;UID=front;Password=PlP2017_#Test;charset=utf8;port=3306;SslMode=None").Options)) { } }
The above methods are the method when we use the data context. We also need to talk about it.Pomelo.EntityFrameworkCore.MySql
After this package, observe the Code performance, mainly in One-to-multiple queries of linq. The Code is as follows:
// One-to-multiple, inefficient var linq2 = from data1 in crm_customers.GetModel () join data2 in crm_customertag.GetModel () on data1.Id equals data2.CustomerId into list select new {name = data1.AccountantName, orders = list,}; var result2 = linq2.Take (10 ). toList ();
Thank you for reading this article!
We will improve some code with performance problems next time!
Back to directory