如何使用 Entity Framework 的 DbContext,


本文转载自微信公众号「码农读书」,作者码农读书 。转载本文请联系码农读书公众号。

微软的 Entity Framework 是一个开源的 对象-关系映射 ORM 框架,它帮助我们打通了 数据库的数据模型 到 代码层的领域模型,Entity Framework 简化了应用程序对数据库的 CURD 操作,而且还向高层屏蔽了数据是如何持久化到数据库的。

说的具体一点就是 DbContext 充当了数据库到领域模型之间的桥梁,这篇文章我们将会讨论如何配置 DbContext 并使用 Entity Framework Core provider 对数据库进行 CURD 操作。

DbContext

DbContext 是 EF 中非常重要的一个组件,它扮演着 Database 的会话连接,使用它可以查询数据到你的 entitys 集合中,也可以通过它将 entitys 保存到底层数据库中, EntityFramework Core 中的 DbContext 拥有如下几个功能模块。

  • 连接管理
  • 查询数据
  • 持久化数据
  • 修改跟踪
  • 缓存
  • 事务管理

要想使用 EntityFramework,需要通过 nuget 引用 Microsoft.EntityFrameworkCore 包,可以通过 Visual Studio 2019 的 NuGet package manager 可视化界面安装 或者 通过 NuGet package manager 命令行工具输入以下命令:

  1. dotnet add package Microsoft.EntityFrameworkCore 

接下来讨论下如何在 ASP.Net Core 中使用 DbContext 。

创建 DbContext

首先创建一个 CustomContext 类,并继承 Entity Framework 中的基类 DbContext,如下代码所示:

  1. public class CustomContext : DbContext 
  2.     { 
  3.         public CustomContext(DbContextOptions options) : base(options) 
  4.         { 
  5.         } 
  6.  
  7.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
  8.         { 
  9.            //Write your code here to configure the context 
  10.         } 
  11.  
  12.         protected override void OnModelCreating(ModelBuilder modelBuilder) 
  13.         { 
  14.             //Write your code here to configure the model 
  15.         } 
  16.     } 

可以看到 CustomContext 的构造函数中接受了 DbContextOptions 类型的参数,该类主要用于对 DbContext 做一些必要的参数配置,当然你也可以在 OnConfiguring() 中对 DbContext 进行配置,接下来的 OnModelCreating() 方法用于对 model 进行配置。

下面我在 CustomContext 中新增几个 DbSet 属性用来表示实体集合,如下代码所示:

  1. public class CustomContext : DbContext 
  2.     { 
  3.         public CustomContext(DbContextOptions options) : base(options) 
  4.         { 
  5.         } 
  6.  
  7.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
  8.         { 
  9.         } 
  10.  
  11.         protected override void OnModelCreating(ModelBuilder modelBuilder) 
  12.         { 
  13.         } 
  14.  
  15.         public DbSet<Author> Authors { get; set; } 
  16.  
  17.         public DbSet<Blog> Blogs { get; set; } 
  18.     } 
  19.  
  20.     public class Author 
  21.     { 
  22.         public int AuthorID { get; set; } 
  23.  
  24.         public string AuthorName { get; set; } 
  25.     } 
  26.  
  27.     public class Blog 
  28.     { 
  29.         public int BlogID { get; set; } 
  30.  
  31.         public string BlogName { get; set; } 
  32.  
  33.         public int AuthorID { get; set; } 
  34.     } 

注册 DbContext 注入到 ASP.NET Core 运行时

要想在 ASP.NET Core 中使用,需要将 CustomerContext 注入到 ServiceCollection 容器中,这里采用 SqlServer 作为底层存储,所以还需要在 NuGet 上引用 Microsoft.EntityFrameworkCore.SqlServer 包,接下来在 Startup.ConfigureServices() 中新增如下代码:

  1. public class Startup 
  2.     { 
  3.         // This method gets called by the runtime. Use this method to add services to the container. 
  4.         public void ConfigureServices(IServiceCollection services) 
  5.         { 
  6.             services.AddControllersWithViews(); 
  7.  
  8.             services.AddDbContext<CustomContext>(options => options.UseSqlServer("Data Source=.; Initial Catalog=MyTest; Trusted_Connection=Yes")); 
  9.         } 
  10.     } 

DbContext 依赖注入

现在 CustomContext 已经注入到容器了,接下来就可以在 HomeController 中通过依赖注入的方式获取 CustomerContext 实例,下面的代码片段展示了如何去实现。

  1. public class HomeController : Controller 
  2.     { 
  3.         ILogger<HomeController> logger; 
  4.         private CustomContext dbContext; 
  5.  
  6.         public HomeController(ILogger<HomeController> logger, CustomContext dbContext) 
  7.         { 
  8.             this.logger = logger; 
  9.             this.dbContext = dbContext; 
  10.  
  11.             dbContext.Database.EnsureCreated(); 
  12.         } 
  13.     } 

上面的代码,我用了 dbContext.Database.EnsureCreated(); 来确保数据库已经成功创建,执行完这句代码之后,数据库将会生成 MyTest 数据库 和 Author,Blog 两张表结构,如下图所示:

接下来在 Index 方法中插入一条记录并查询,效果如下:

这就是配置 EF 所要做的所有事情,现在你可以利用 CustomContext 去所 CURD 操作了,DbContext 在概念上类似 ObjectContext,表示一个 UnitOfWork 组合单元,并且 EF 是DDD领域的一个实现案例,DbContext 的职责就是负责 应用程序 和 数据库 之间的交互,关于 Entity Framework Core 的更多特性,我会放到后面的文章中和大家一起分享。

译文链接:https://www.infoworld.com/article/3311737/how-to-use-the-dbcontext-in-entity-framework-core.html

相关内容