ASP.NET Core中使用GraphQL - 第六章 使用EF Core作为持久化仓储

 ASP.NET Core中使用GraphQL


本篇中我将演示如何配置持久化仓储,这里原文中是使用的Postgres, 这里我改用了EF Core For SqlServer。本文的例子需要在上一篇的代码基础上修改。没有代码的同学,可以去https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part%20V下载。

之前我们编写了一个DataStore类,里面硬编码了一个数据集合,这里我们希望改用依赖注入的方式进行解耦,所以首先我们需要创建一个抽象接口IDataStore

public interface IDataStore {     IEnumerable<Item> GetItems();     Item GetItemByBarcode(string barcode); }

由于接下来我们需要使用EF Core, 所以这里我们需要添加一个EF Core的上下文类ApplicationDbContext

public class ApplicationDbContext : DbContext {     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)     {      }          public DbSet<Item> Items { get; set; }          protected override void OnModelCreating(ModelBuilder modelBuilder)     {         modelBuilder.Entity<Item>().ToTable("Items");         modelBuilder.Entity<Item>().HasKey(p => p.Barcode);              modelBuilder.Entity<Item>().HasData(new Item {              Barcode = "123",              Title = "Headphone",              SellingPrice = 50 });                      modelBuilder.Entity<Item>().HasData(new Item {              Barcode = "456",              Title = "Keyboard",              SellingPrice = 40 });         modelBuilder.Entity<Item>().HasData(new Item {              Barcode = "789",              Title = "Monitor",              SellingPrice = 100 });          base.OnModelCreating(modelBuilder);     } }

这里为了导入一些初始数据,我们在OnModelCreating方法中使用HasData方法添加了3个初始数据。

下面我们修改DataStore类, DataStore应该实现IDataStore接口, 其中的

关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信