本文转自: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+

Copy
C#
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+

Copy
C#
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+

Copy
C#
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"+

Copy
C#
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+

Copy
C#
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+

Copy
C#
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
:base(options)
{ } public DbSet<Blog> Blogs { get; set; }
}

Application code (in ASP.NET Core)+

Copy
C#
public MyController(BloggingContext context)

Application code (using ServiceProvider directly, less common)+

Copy
C#
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:+

Copy
C#
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

[转] EF Configuring a DbContext的更多相关文章

  1. EF Core中DbContext可以被Dispose多次

    我们知道,在EF Core中DbContext用完后要记得调用Dispose方法释放资源.但是其实DbContext可以多次调用Dispose方法,虽然只有第一次Dispose会起作用,但是DbCon ...

  2. 在 ef 中执行 DbContext.Table.AddRange(Enitites).ToList() 会发生什么

    在 ef 中执行 DbContext.Table.AddRange(Enitites).ToList() 会发生什么 昨天和朋友摸鱼,无意之间聊到了执行 DbContext.Table.AddRang ...

  3. Asp.net WebApi + EF 单元测试架构 DbContext一站到底

    其实关于webapi和Ef service的单元测试我以前已经写过相关文章,大家可以参考: Asp.net WebAPI 单元测试 单元测试 mock EF 中DbContext 和DbSet Inc ...

  4. EF Core 中DbContext不会跟踪聚合方法和Join方法返回的结果,及FromSql方法使用讲解

    EF Core中: 如果调用Queryable.Count等聚合方法,不会导致DbContext跟踪(track)任何实体. 此外调用Queryable.Join方法返回的匿名类型也不会被DbCont ...

  5. 第三节:EF Core上下文DbContext相关配置和生命周期

    一. 配置相关 1. 数据库连接字符串的写法 (1).账号密码:Server=localhost;Database=EFDB01;User ID=sa;Password=123456; (2).win ...

  6. EF中的DbContext类

    使用先前的数据上下文,可以通过使用LINQ查询,按字母顺序检索出所有专辑,代码如下

  7. EF Core 快速上手——创建应用的DbContext

    系列文章 EF Core 快速上手--EF Core 入门 EF Core 快速上手--EF Core的三种主要关系类型 本节导航 定义应用的DbContext 创建DbContext的一个实例 创建 ...

  8. .NetCore之EF跳过的坑

    我在网上看到很多.netCore的信息,就动手自己写一个例子测试哈,但是想不到其中这么多坑: 1.首先.netCore和EF的安装就不用多说了,网上有很多的讲解可以跟着一步一步的下载和安装,但是需要注 ...

  9. EF – 问题集锦

    1.对一个或多个实体的验证失败.有关详细信息,请参见“EntityValidationErrors”属性 在EF5.0修改实体的时候,出现“对一个或多个实体的验证失败.有关详细信息,请参见“Entit ...

随机推荐

  1. div+css知识点(2)

    文字溢出 显示省略号的 关键的三句代码text-overflow:ellipsis; -o-text-overflow:ellipsis; overflow:hidden;文字缩进的代码是什么text ...

  2. 趣味C程序100.1 .1 绘制余弦曲线

    说明:1.本问题来源于<C语言经典.趣味.实用程序设计编程百例精解>,所有程序为本人自己编写.与原程序不同之处作有标记. 2.本系列所有程序均使用codeblocks编译,操作系统为Win ...

  3. LA 3882

    动态规划: 白书上的题,看了好久看不懂刘汝佳的解法: 在网上无意中看到了大神的思路,比较好理解,膜拜! 他的思路是这样的: 设d[i]是n个数按顺时针方向分别从0开始编号,第一次删除0,以后每k个数删 ...

  4. Werkzeug教程

    http://chaoxz2005.blog.163.com/blog/static/15036542012863405266/ http://www.dajo.com.cn/a/boke/pytho ...

  5. c#回调函数写法

    添加一个cs文件,在里面定义回调 using System; using System.Collections.Generic; using System.Linq; using System.Web ...

  6. WebSocket能干啥

    ------这东西到底有什么用途,仔细看了说明,还是不明所以.楼上几位能不能介绍一下实际使用的场景?? 1.可以实现 服务器端(delphi&lazarus@win)<->手机端  ...

  7. Condition-线程通信更高效的方式

    接近一周没更新<Java线程>专栏了,主要是这周工作上比较忙,生活上也比较忙,呵呵,进入正题,上一篇讲述了并发包下的Lock,Lock可以更好的解决线程同步问题,使之更面向对象,并且Rea ...

  8. java学习面向对象之父子构造函数初始化

    在之前讲到java面向对象继承的时候,我们只讲到了两个比较重要的知识点,一个是父子类当中有同名的成员变量,这个时候,我们引入了super这个关键字来区分这两个同名成员变量,除此之外,我们还讲到了父子同 ...

  9. WordPress特制字符串URL重定向限制绕过漏洞

    漏洞版本: WordPress 3.6 漏洞描述: Bugtraq ID:62344 CVE ID:CVE-2013-4339 WordPress是一种使用PHP语言开发的博客平台,用户可以在支持PH ...

  10. Delphi 调试WEBService程序(ISAPI或CGI) 把Web App Debugger executable转换成 ISAPI/NSAPI

      1.新建一个web工程,请选中最下面一项:Web App Debugger executable,Coclass name我们设为demo1: 2.在弹出的WebModule2中右击,在弹出的Ac ...