[转] EF Configuring a DbContext
本文转自:https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext
Note
This documentation is for EF Core. For EF6.x, see Entity Framework 6.+
This article shows patterns for configuring a DbContext with DbContextOptions. Options are primarily used to select and configure the data store.+
Configuring DbContextOptions
DbContext must have an instance of DbContextOptions in order to execute. This can be configured by overriding OnConfiguring, or supplied externally via a constructor argument.+
If both are used, OnConfiguring is executed on the supplied options, meaning it is additive and can overwrite options supplied to the constructor argument.+
Constructor argument
Context code with constructor+
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
Tip
The base constructor of DbContext also accepts the non-generic version of DbContextOptions. Using the non-generic version is not recommended for applications with multiple context types.+
Application code to initialize from constructor argument+
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Filename=./blog.db");
using (var context = new BloggingContext(optionsBuilder.Options))
{
// do stuff
}
OnConfiguring
Warning
OnConfiguring occurs last and can overwrite options obtained from DI or the constructor. This approach does not lend itself to testing (unless you target the full database).+
Context code with OnConfiguring+
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=./blog.db");
}
}
Application code to initialize with "OnConfiguring"+
using (var context = new BloggingContext())
{
// do stuff
}
Using DbContext with dependency injection
EF supports using DbContext with a dependency injection container. Your DbContext type can be added to the service container by using AddDbContext<TContext>.+
AddDbContext will add make both your DbContext type, TContext, and DbContextOptions<TContext> to the available for injection from the service container.+
See more reading below for information on dependency injection.+
Adding dbcontext to dependency injection+
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options => options.UseSqlite("Filename=./blog.db"));
}
This requires adding a constructor argument to you DbContext type that accepts DbContextOptions.+
Context code+
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
:base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
Application code (in ASP.NET Core)+
public MyController(BloggingContext context)
Application code (using ServiceProvider directly, less common)+
using (var context = serviceProvider.GetService<BloggingContext>())
{
// do stuff
}
var options = serviceProvider.GetService<DbContextOptions<BloggingContext>>();
Using IDbContextFactory<TContext>
As an alternative to the options above, you may also provide an implementation of IDbContextFactory<TContext>. EF command line tools and dependency injection can use this factory to create an instance of your DbContext. This may be required in order to enable specific design-time experiences such as migrations.+
Implement this interface to enable design-time services for context types that do not have a public default constructor. Design-time services will automatically discover implementations of this interface that are in the same assembly as the derived context.+
Example:+
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace MyProject
{
public class BloggingContextFactory : IDbContextFactory<BloggingContext>
{
public BloggingContext Create()
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Filename=./blog.db");
return new BloggingContext(optionsBuilder.Options);
}
}
}
More reading
Read Getting Started on ASP.NET Core for more information on using EF with ASP.NET Core.
Read Dependency Injection to learn more about using DI.
Read Testing with InMemory for more information.
Read Understanding EF Services for more details on how EF uses dependency injection internally.
[转] EF Configuring a DbContext的更多相关文章
- EF Core中DbContext可以被Dispose多次
我们知道,在EF Core中DbContext用完后要记得调用Dispose方法释放资源.但是其实DbContext可以多次调用Dispose方法,虽然只有第一次Dispose会起作用,但是DbCon ...
- 在 ef 中执行 DbContext.Table.AddRange(Enitites).ToList() 会发生什么
在 ef 中执行 DbContext.Table.AddRange(Enitites).ToList() 会发生什么 昨天和朋友摸鱼,无意之间聊到了执行 DbContext.Table.AddRang ...
- Asp.net WebApi + EF 单元测试架构 DbContext一站到底
其实关于webapi和Ef service的单元测试我以前已经写过相关文章,大家可以参考: Asp.net WebAPI 单元测试 单元测试 mock EF 中DbContext 和DbSet Inc ...
- EF Core 中DbContext不会跟踪聚合方法和Join方法返回的结果,及FromSql方法使用讲解
EF Core中: 如果调用Queryable.Count等聚合方法,不会导致DbContext跟踪(track)任何实体. 此外调用Queryable.Join方法返回的匿名类型也不会被DbCont ...
- 第三节:EF Core上下文DbContext相关配置和生命周期
一. 配置相关 1. 数据库连接字符串的写法 (1).账号密码:Server=localhost;Database=EFDB01;User ID=sa;Password=123456; (2).win ...
- EF中的DbContext类
使用先前的数据上下文,可以通过使用LINQ查询,按字母顺序检索出所有专辑,代码如下
- EF Core 快速上手——创建应用的DbContext
系列文章 EF Core 快速上手--EF Core 入门 EF Core 快速上手--EF Core的三种主要关系类型 本节导航 定义应用的DbContext 创建DbContext的一个实例 创建 ...
- .NetCore之EF跳过的坑
我在网上看到很多.netCore的信息,就动手自己写一个例子测试哈,但是想不到其中这么多坑: 1.首先.netCore和EF的安装就不用多说了,网上有很多的讲解可以跟着一步一步的下载和安装,但是需要注 ...
- EF – 问题集锦
1.对一个或多个实体的验证失败.有关详细信息,请参见“EntityValidationErrors”属性 在EF5.0修改实体的时候,出现“对一个或多个实体的验证失败.有关详细信息,请参见“Entit ...
随机推荐
- python 运行 hadoop 2.0 mapreduce 程序
要点:#!/usr/bin/python 因为要发送到各个节点,所以py文件必须是可执行的. 1) 统计(所有日志)独立ip数目,即不同ip的总数 ####################本地测试## ...
- 转-Python optionParser模块的使用方法
Python 有两个内建的模块用于处理命令行参数: 一个是 getopt,<Deep in python>一书中也有提到,只能简单处理 命令行参数: 另一个是 optparse,它功 ...
- Node.js权威指南 (6) - 在Node.js中操作文件系统
6.1 同步方法与异步方法 / 856.2 对文件执行读写操作 / 86 6.2.1 文件的完整读写 / 86 6.2.2 从指定位置处开始读写文件 / 916.3 创建与读取目录 / 97 6.3. ...
- 每天一个linux命令:mkdir
linux mkdir 命令用来创建指定的名称的目录,要求创建目录的用户在当前目录中具有写权限,并且指定的目录名不能是当前目录中已有的目录. 1.命令格式: mkdir [选项] 目录... 2.命令 ...
- 笔记-人老了-github
其实GITHUB是很不错的,虽然之前的JD泄露那件事情,后果很严重. 但是作为个人使用很不错的. github使用入门: 1:申请一个帐号 2:github使用ssh推送的.(ssh走的是加密) 所以 ...
- IIS7 上传 下载文件大小限制的设置
IIS7 上传 下载文件大小限制的设置 本文来自IISBOY网 一.找到修改大小的配置文件和配置节点 本文来自IISBOY网 打开你系统盘(我是C盘),找到 C:\Windows\System32\i ...
- 折腾iPhone的生活——AirDrop的使用
AirDrop是iOS一个非常大的亮点,其实说是这么说了,但是事实上AirDrop并没有想象中那么好用. AirDrop就是一个用于无线传输文件的方式,实质性跟蓝牙没有太大区别,但是比蓝牙好用,有点像 ...
- LOL游戏程序中对一些函数的Hook记录(Win10 x64)
[PC Hunter Standard][League of Legends.exe-->Ring3 Hook]: 108Hooked Object Hook Address and Locat ...
- HDU 1230 火星A+B
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1230 水题模拟一道,主要考验代码能力,刷完题就感觉自己还是太弱了. #include<cmath ...
- iptables vpn