在Apworks数据服务中使用基于Entity Framework Core的仓储(Repository)实现
《在ASP.NET Core中使用Apworks快速开发数据服务》一文中,我介绍了如何使用Apworks框架的数据服务来快速构建用于查询和管理数据模型的RESTful API,通过该文的介绍,你会看到,使用Apworks框架开发数据服务是何等简单快捷,提供的功能也非常多,比如对Hypermedia的支持,以及提供丰富的异常信息和调用栈信息。另外,Apworks数据服务可以支持各种类型的仓储(Repository)实现,在该文的案例中,我使用了MongoDB作为仓储的实现,这是为了快速方便地演示数据服务的搭建过程。如果你所使用的是关系型数据库,也没有关系(意思是不要紧,不是说数据没有关系。。。-_-!!!),基于Entity Framework Core的仓储实现能够满足你的需求。
需要注意的一个问题
在以前老版本的Apworks中,仓储的接口是支持饥饿加载的,也就是说,在延迟加载被启用的时候,仓储允许通过显式指定一系列的对象属性,当主对象被返回时,这些属性所指向的子对象也会同时返回。这样的设计在当时的场景下是合理的,因为是否需要加载某些属性是可以在程序中指定的,对于类似MongoDB的仓储实现,它没有延迟加载的概念,因此可以忽略这个参数。在Apworks数据服务中,由于仓储的操作会直接被DataServiceController调用,而相关的查询条件都是来自于RESTful API的,因此,很难在API的层面来确定某些聚合的对象属性是否需要饥饿加载(Eager Loading)。另一方面,禁用延迟加载又会产生性能问题,因此,在当前版本的实现中,我还没有考虑好用何种方式来解决这个问题。或许可以通过HTTP Header来指定需要饥饿加载的属性路径,但这是另一个问题。总之,在接下来的案例中,你将看到,虽然数据已经添加成功,但在返回的结果里,被聚合的子对象将无法返回。我会设法解决这个问题。
案例:Customer Service
假设我们需要使用Entity Framework快速构建一个支持增删改查操作的数据服务(Data Service),并希望该服务能够在容器中运行,我们可以首先新建一个ASP.NET Core的应用程序,然后依照下面的步骤进行:
- 向ASP.NET Core应用程序添加以下NuGet包引用:
 - Apworks.Integration.AspNetCore
 - Apworks.Repositories.EntityFramework
 - Microsoft.EntityFrameworkCore.SqlServer(在本案例中我们使用SQL Server,当然也可以使用PostgreSQL或者MySQL等)
 - Microsoft.EntityFrameworkCore.Tools
 - 新建领域模型,向ASP.NET Core应用程序中添加Customer和Address类:     
public class Address
{
public Guid Id { get; set; } public string Country { get; set; } public string State { get; set; } public string City { get; set; } public string Street { get; set; } public string ZipCode { get; set; }
} public class Customer : IAggregateRoot<Guid>
{
public Guid Id { get; set; } public string Name { get; set; } public string Email { get; set; } public Address ContactAddress { get; set; }
} - 新建一个DbContext类,用于指定数据库的访问方式,以及对模型对象/数据表结构进行映射:
public class CustomerDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.ToTable("Customers")
.HasKey(x => x.Id);
modelBuilder.Entity<Customer>()
.Property(x => x.Id)
.ForSqlServerHasDefaultValueSql("newid()");
modelBuilder.Entity<Customer>()
.Property(x => x.Name)
.IsUnicode()
.IsRequired()
.HasMaxLength(20);
modelBuilder.Entity<Customer>()
.Property(x => x.Email)
.IsUnicode()
.IsRequired()
.HasMaxLength(50);
modelBuilder.Entity<Address>()
.ToTable("Addresses")
.HasKey(x => x.Id);
modelBuilder.Entity<Address>()
.Property(x => x.Id)
.ForSqlServerHasDefaultValueSql("newid()"); base.OnModelCreating(modelBuilder);
} protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=localhost\sqlexpress; Database=CustomerService; Integrated Security=SSPI;");
}
} - 打开Package Manager Console,并在解决方案资源管理器中将当前ASP.NET Core项目设置为启动项目(注意:这一点非常重要)。然后依次执行:
Add-Migration InitialCreate
Update-Database成功完成这一步骤后,我们的数据库就已经准备好了。事实上,以上步骤都是开发一个Entity Framework Core应用程序所必须经历的标准步骤,目前还没有用到Apworks的功能(当然,将Customer定义成聚合根除外)。接下来,我们开始实现并配置Apworks数据服务,接下来的步骤跟基于MongoDB的实现非常类似。
 - 在ASP.NET Core应用程序的Controllers文件夹下,新建一个CustomersController,从DataServiceController继承:
public class CustomersController : DataServiceController<Guid, Customer>
{
public CustomersController(IRepositoryContext repositoryContext) : base(repositoryContext)
{
}
} - 打开Startup.cs文件,分别修改ConfigureServices和Configure方法,如下:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddScoped<CustomerDbContext>();
services.AddApworks()
.WithDataServiceSupport(new DataServiceConfigurationOptions(sp =>
new EntityFrameworkRepositoryContext(sp.GetService<CustomerDbContext>())))
.Configure();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(); app.EnrichDataServiceExceptionResponse(); app.UseMvc();
}与MongoDB实现不同的是,在使用EntityFrameworkRepositoryContext之前,我们需要通过services.AddScoped方法,将CustomerDbContext以Scoped生命周期注册到IoC容器中,而在初始化EntityFrameworkRepositoryContext时,使用Service Provider的GetService方法进行Resolve,这样就能确保每次HTTP请求完成时,资源都能成功释放。
 
下面,我们来测试一下这个Apworks数据服务。在Visual Studio 2017中按下Ctrl+F5,直接运行ASP.NET Core应用程序,使用你喜欢的RESTful客户端软件,向/api/Customers进行POST操作,可以看到,Customer可以被成功创建,Customer Id即刻返回:

让我们再GET一下试试(注意:返回的ContactAddress是null,而事实上数据库里是有值的。这里返回null的原因是因为我们没有在Entity Framework中通过Include调用进行饥饿加载(Eager Loading),接下来会尝试解决这个问题):

除了ContactAddress在GET请求中返回为null之外,其它各种行为,包括数据服务所支持的API接口、调用方式等,都与之前MongoDB的实现完全相同。
源代码
本文案例中的源代码可以在Apworks Examples开源项目中找到。本案例的源代码在Apworks.Examples.CustomerService.EntityFramework目录下。
总结
本文带领着大家一起预览了Apworks数据服务对Entity Framework Core的支持,使得Apworks数据服务不仅可以使用MongoDB等NoSQL存储方案,也可以使用关系型数据库存储方案,而且编程体验也是几乎相同的。这对于不同应用场景下微服务的实现是非常有帮助的。虽然在Entity Framework Core的实现中,目前有些瑕疵,但我会尽快解决这个问题。
在Apworks数据服务中使用基于Entity Framework Core的仓储(Repository)实现的更多相关文章
- 创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表
		
创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表 创建数据模型类(POCO类) 在Models文件夹下添 ...
 - vs for Mac中的启用Entity Framework Core .NET命令行工具
		
在vs for Mac的工具菜单中已没有了Package Manager Console. 我们可以通过以下方法使用Entity Framework Core .NET命令行工具: 1.添加Nuget ...
 - 请问在 .NET Core 中如何让 Entity Framework Core 在日志中记录由 LINQ 生成的SQL语句?
		
using dotNET.Core; using Microsoft.Extensions.Logging; using System; using System.Collections.Generi ...
 - Apworks框架实战(六):使用基于Entity Framework的仓储基础结构
		
在前面的章节中,我们已经设计了一个简单的领域模型,接下来我们希望能够实现领域模型的持久化及查询.在Apworks中,实现了面向Entity Framework.NHibernate以及MongoDB的 ...
 - Entity Framework Core  for Console
		
包 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCor ...
 - UWP开发之ORM实践:如何使用Entity Framework Core做SQLite数据持久层?
		
选择SQLite的理由 在做UWP开发的时候我们首选的本地数据库一般都是Sqlite,我以前也不知道为啥?后来仔细研究了一下也是有原因的: 1,微软做的UWP应用大部分也是用Sqlite.或者说是微软 ...
 - Working with Data »  Getting started with ASP.NET Core and Entity Framework Core using Visual Studio »  更新关系数据
		
Updating related data¶ 7 of 7 people found this helpful The Contoso University sample web applicatio ...
 - 浅析Entity Framework Core中的并发处理
		
前言 Entity Framework Core 2.0更新也已经有一段时间了,园子里也有不少的文章.. 本文主要是浅析一下Entity Framework Core的并发处理方式. 1.常见的并发处 ...
 - Working with Data »  Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 读取关系数据
		
Reading related data¶ 9 of 9 people found this helpful The Contoso University sample web application ...
 
随机推荐
- 5.Lock接口及其实现ReentrantLock
			
jdk1.7.0_79 在java.util.concurrent.locks这个包中定义了和synchronized不一样的锁,重入锁——ReentrantLock,读写锁——ReadWriteLo ...
 - Building [Security] Dashboards w/R & Shiny + shinydashboard(转)
			
Jay & I cover dashboards in Chapter 10 of Data-Driven Security (the book) but have barely mentio ...
 - Docker -  运行 containers 使用在 swarm 模式下创建的 overlay 模式的 network
			
前言 在Docker engine v1.12, 使用Swarm可以方便的创建overlay模式的网络,但是它只能被swarm下面的service所使用的,相对于container,这个网络是完全隔离 ...
 - arcgis sde 导出栅格文件失败,提示“Database user name and current user schema do not match ”.
			
具体错误/警告如下: 翻译一下:数据库用户名和当前用户数据库对象的集合不匹配 没有空间参考存在 数据库表没找到 主要还是第一句的问题. 解决方法:切换当前sde账户为能够写入sde的账户,这块不是很了 ...
 - jQuery插件 -- 图片随页面滚动fixed
			
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
 - FTP主动模式和被动模式的区别
			
基础知识: FTP只通过TCP连接,没有用于FTP的UDP组件.FTP不同于其他服务的是它使用了两个端口, 一个数据端口和一个命令端口(或称为控制端口).通常21端口是命令端口,20端口是数据端口.当 ...
 - 黑马程序员:3分钟带你读懂C/C++学习路线
			
随着互联网及互联网+深入蓬勃的发展,经过40余年的时间洗礼,C/C++俨然已成为一门贵族语言,出色的性能使之成为高级语言中的性能王者.而在今天,它又扮演着什么样重要的角色呢?请往下看: 后端服务器,移 ...
 - Sizzle 源码分析 (二)
			
在Sizzle函数中,如果能快速处理或者通过querySelector处理,那么就使用它处理.否则使用select函数处理 . select函数 select = Sizzle.select = fu ...
 - canvas实现视频截图
			
截取视频当前播放画面,直接上源码. <body> <div class="container"> <video id="test" ...
 - 破解 Adobe 系列的最佳方法,手把手教
			
此方法是个人认为最方便的而且最安全的方法(可以避免下载到可能捆绑病毒的破解版本) 1.首先到Adobe的官网上下载 Creative Cloud: 打开官网上creative cloud 的下载页面: ...