[转] 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+

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

时间: 2024-10-09 09:44:57

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

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

其实关于webapi和Ef service的单元测试我以前已经写过相关文章,大家可以参考: Asp.net WebAPI 单元测试 单元测试 mock EF 中DbContext 和DbSet Include 先看一下项目结构图: 这个demo非常简单,UTWebApi.Data 是纯粹的数据定义,UTWebApi.Service是我们的业务服务逻辑层,UTWebApi 是我们webapi的实现,UTWebApi.Tests就是测试项目. 数据层: BloggerDbContext的构造函数一般

EF Core 中DbContext不会跟踪聚合方法和Join方法返回的结果

EF Core中: 如果调用Queryable.Count等聚合方法,不会导致DbContext跟踪(track)任何实体. 此外调用Queryable.Join方法返回的匿名类型也不会被DbContext所跟踪(实测调用Queryable.Join方法返回EF Core中的实体类型也不会被DbContext所跟踪). Queryable.Count等聚合方法和Queryable.Join方法返回的结果不会被跟踪,原因是因为这两种方法返回的结果类型并没有被DbContext的OnModelCre

使用EF 的简单的增删改查

using DAL; using Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLL { public class InfoManage { private BaseDal db; public InfoManage(BaseDal dal) { this.db = dal;

ASP.NET MVC 5 + EF 6 入门教程 (5) Model和Entity Framework

文章来源: Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc-5-ef-6-get-started-model.html 上一节:ASP.NET MVC 5 入门教程 (4) View和ViewBag 源码下载:点我下载 MVC中的Model是用来给View提供显示数据的对象. 这里我们首先创建一个Model对象. 在解决方案资源管理器中右键点击Models文件夹,选择添加->类.添加一个名为Employee.cs的Model类.Models文件夹

模拟EF CodeFist 实现自己的ORM

一.什么是ORM 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术. 简单来说,ORM 是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中或者将数据库的数据拉取出来 二.EF基本原理 1.EF 是微软以 ADO.NET 为基础所发展出来的对象关系对应 (O/R Mapping) 解决方案 2.EF 核心对象DbContext,其基本原理是,实现系统IQueryable<T

EF &ndash; 问题集锦

  1.对一个或多个实体的验证失败.有关详细信息,请参见"EntityValidationErrors"属性   在EF5.0修改实体的时候,出现"对一个或多个实体的验证失败.有关详细信息,请参见"EntityValidationErrors"属性这个错误 修改: SaveChanges前先关闭验证实体有效性(ValidateOnSaveEnabled)这个开关   db.Configuration.ValidateOnSaveEnabled = fals

EF的Model First

一,添加ADO.NET实体数据模型(即edmx) 1,添加edmx 新建一个类库项目,项目中添加新项,选择数据/ADO.NET实体数据模型,如下图. 点击添加,实体数据模型向导窗口,选择空EF设计器模型,然后点击完成,即创建edmx文件成功. 2,添加实体模型 接下来,往edmx设计器中添加实体模型.在设计器中右键新增/实体,或者从工具箱中拖一个实体过来.二,添加T4模板(包括DbContext和Entity的) 1,添加T4模板 项目中添加新项,选择数据/EF 6.x DbContext生成器

NopCommerce用core重写ef

最近看了NopCommerce源码,用core学习着写了一个项目,修改的地方记录下.项目地址 NopCommerce框架出来好久了.18年的第一季度 懒加载出来后也会全部移动到.net core.那么就更好玩了.   项目内容 模仿部分 分层模式 引擎机制 DI容器 EF 仓储模式 Mapping 部分修改 .net core 重写类库 EFcore mysql 动态加载dbset 当然NopCommerce还包含很多特技:Plugin,Seo,订阅发布,theme切换等等.这些后期再维护进去.

ASP.NET Core 配置 EF 框架服务 - ASP.NET Core 基础教程 - 简单教程,简单编程

原文:ASP.NET Core 配置 EF 框架服务 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 配置 EF 框架服务 上一章节中我们了解了 Entity Framework 的基本工作原理和 DbContext ,我们也创建了一个自己的 HelloWorldDBContext. 本章节我们就来讲讲如何设置我们的 EF 框架来链接到 SQLite 数据库 配置 EF 框架服务 要让我们的 EF 框架的 DBContext 能够运行起来,我们需要更改一