In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)06/01 Report--
Explicitly create a DbContext instance through the constructor with OnConfiguring
This must be our easiest way, by calling the class inherited from DbContext and calling its no-parameter constructor, and we need to keep in mind that we need to release it every time we instantiate it, that is, wrap its instance in Using. As follows:
Using (var context = new EFCoreContext ()) {}
Then configure the EF Core context instance by overloading OnConfiguring, as shown below.
Public class EFCoreContext: DbContext {protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) = > optionsBuilder.UseSqlServer (@ "Server=.;Database=EFTest;Trusted_Connection=True;");}
[note]: the overloaded OnConfiguring is different from the OnModelCreating creation model in the previous EF version. The OnModelCreating creation model context is instantiated only once, but OnConfiguring is called every time a context is instantiated, so OnConfiguring can make full use of the constructor or other data in the context.
There are many constructors for context in EF 6.x, such as passing parameters to a connection string, which are also possible in EF Core 1.1:
Public class EFCoreContext: DbContext {private readonly string _ connectionString; public EFCoreContext (string connectionString) {_ connectionString = connectionString;} protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) = > optionsBuilder.UseSqlServer (_ connectionString);}
Using DbContextOptions without dependency injection
In the constructor of DbContext, we can accept a DbContextOptions object, which is mainly used when creating a DbContext instance in the DI container. Of course, it can also be explicitly called to isolate the context by creating a DbCOntextOptions object, so we can use it to use the same options for each instance of the context, as follows:
Public class EFCoreContext: DbContext {public EFCoreContext (DbContextOptions options): base (options) {}}
Public class HomeController: Controller {private static DbContextOptions _ contextOptions; public IActionResult Index () {_ contextOptions = new DbContextOptionsBuilder () .UseSqlServer (") .options; using (var context = new EFCoreContext (_ contextOptions)) {} return View ();}}
Seeing here we see that there is really no need to overload OnConfiguring, but OnConfiguring will still be overloaded and called all the time, why, because we inject context into the configuration, it calls the constructor and adjusts the OnConfiguring appropriately at the same time.
Create a DbContext instance using dependency injection
All we have to do is register the context type in the DI container, and then it will be parsed by the DI container, but it doesn't matter if we register the context with the DI container, you should also note the following two points. This is what we typically do by injecting it into a DI container.
Public class EFCoreContext: DbContext {public EFCoreContext (DbContextOptions options): base (options) {}}
Services.AddDbContext (options = > {options.UseSqlServer (sqlStr, d = > d.MigrationsAssembly ("StudyEFCore"));})
It's reasonable and legal, but why can't it be used like this?
Services.AddSingleton ()
Isn't it okay to inject in the form of a singleton? if you do, you can wait for the program to crash, because the context DbContext is not thread-safe, that is, it cannot be registered with a singleton to use no extra locks. Then, after injecting it into the DI container, we still use Using to wrap it when we use it. Don't think that injecting it into the DI container will do everything for you. The DI container will not automatically handle it for you. Of course, if you only use it temporarily in the DI container, there will usually be no disaster. So we need to keep in mind the following two points.
(1) after the context is injected into the DI container, it is still included with Using when using DbContext, because the DI container does not automatically release it.
(2) DbContext is not thread-safe, even in the DI container, it is guaranteed that there will be no problem, in most cases there will be no problem, don't worry.
DI with DbContextOptions creates DbContext instance
It's still useful for us to register an DbContextOptions instance in DI. It will only be created once and used as a singleton. For example, we can initialize the data as follows
Public class EFCoreContext: DbContext {public EFCoreContext (DbContextOptions options): base (options) {}}
Private static IServiceProvider _ serviceProvider; public IActionResult Index () {var contextOptions = new DbContextOptionsBuilder () .UseSqlServer (") .options; var services = new ServiceCollection () .AddSingleton (contextOptions) .AddScoped (); _ serviceProvider = services.BuildServiceProvider (); return View ();}
The EFCoreContext context will now be parsed by the DI container and will be injected into its constructor by injecting the DbContextOptions instance. This _ serviceProvider is the provider of the injection context. We also said above that we can initialize the data and how to initialize Ni. Let's take a look. The following configuration methods are used in Startup.cs:
Public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {.... }
This app has the following properties:
What is not found is the abstract property of all injected services, and we can initialize the data in this method by converting it to EFCoreContext. Let's see.
Private static EFCoreContext context; public static void Initialize (IServiceProvider serviceProvider) {context = (EFCoreContext) serviceProvider.GetService (typeof (EFCoreContext)) / / do your something}
Create a DbContext instance using generic DbContextOptions
All of the above are non-generic DbContextOptions objects, as follows:
Public class EFCoreContext: DbContext {public EFCoreContext (DbContextOptions options): base (options) {} protected override void OnModelCreating (ModelBuilder modelBuilder) {modelBuilder.AddEntityConfigurationsFromAssembly (GetType (). GetTypeInfo () .Assembly);}}
But there is also a generic version of DbContextOptions in its parameters, so what are generics used for? let's take a look at the following example:
Public class EFCoreContext1: DbContext {public EFCoreContext1text1 (DbContextOptions options): base (options) {} public class EFCoreContext2: DbContext {public EFCoreContext2 (DbContextOptions options): base (options) {}} var contextOptions1 = new DbContextOptionsBuilder () .UseSqlServer (connectionString1) .options Var contextOptions2 = new DbContextOptionsBuilder () .UseSqlServer (connectionString2) .options; var services = new ServiceCollection () .AddSingleton (contextOptions1) .AddScoped () .AddSingleton (contextOptions2) .AddScoped (); _ serviceProvider = services.BuildServiceProvider ()
See what? if there are multiple context types registered in the DI container, we can allow the type of each context to depend on its own Options. Parsing EFCoreContext1 will cause DbContextOptions to be injected, just as parsing EFCoreContext2 will cause DbContextOptions to be injected.
Use AddDbContext to create an DbContext instance
Register DbContext and DbContextOptions instances with AddDbContext syntax sugar. As follows:
Var services = new ServiceCollection () .AddDbContext (b = > b.UseSqlServer (connectionString))
By default, register EFCoreContext as a scope, register DbContextOptions as a singleton, and you can change to register EFCoreContext as a singleton, which we have discussed above. Well, at this point, we must know several ways to create EF Core context instances, which can be summarized into the following three points.
(1) call the context constructor directly and overload OnConfiguring to create the context instance.
(2) pass the DbContextOptions to the constructor to create the context instance.
(3) create a context instance through the DI container.
Using DbContextOptionsBuilder to configure a DbContext and eventually construct a DbContextOptions object can also be passed to the constructor of the DbContext by overloading the OnConfiguring method or by constructing the options, whether through the no-parameter constructor or through the DbContextOptions to the constructor of the context, or by injecting DbContext into the DI container, there is no essential difference, except that the DI is a little easier and the forcing is higher. Nothing else.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.