在这个过程中,我们将遵循我们在处理数据库时通常使用的相同方法,即
首先,我们从安装所需的 NuGet 包开始。
- 打开“项目”菜单并选择“管理 NuGet 包”。
- 查询”C1. AdoNet. Json“NuGet 包并单击安装。
创建连接字符串为了连接我们的数据源,我们需要一个连接字符串。我们将使用C1JsonConnectionStringBuilder来创建我们的连接字符串。创建连接字符串,需要 3 项:
- JSON DataModel:它指定了用于读取 JSON 数据的访问机制。指定 DataModel,让我们配置如何将对象数组建模为表。可用的不同数据模型是——顶级文档模型、扁平模型、关系模型。
- Uri:指定 JSON 资源位置的 URI。您可以连接到本地文件或 http 流。
- JSON Path : 指定从哪个节点读取 json 内容
下面显示了为数据创建连接字符串的示例:
- public static class Utils
- {
- public static string JsonDataPath => "Data\\EmployeesData.json";
- public static C1JsonConnectionStringBuilder JsonConnectionBuilder { get; }
- static Utils()
- {
- JsonConnectionBuilder = new C1JsonConnectionStringBuilder()
- {
- DataModel = "Document",
- Uri = JsonDataPath,
- JsonPath = "$.employees"
- };
- }
- }
复制代码
类似地,以下显示了为关系数据创建连接字符串:
- public static class Utils
- {
- public static string JsonCustomerDataPath => "Data\\CustomersData.json";
- public static C1JsonConnectionStringBuilder CustomerDataConnectionStringBuilder { get; }
- static Utils()
- {
- CustomerDataConnectionStringBuilder = new C1JsonConnectionStringBuilder()
- {
- DataModel = "Relational",
- Uri = JsonCustomerDataPath,
- JsonPath = "$.customers;$.customers.Transactions"
- };
- }
- }
复制代码
如何创建连接对象现在,我们已经获得了连接字符串,所以下一步是使用C1JsonConnection类初始化一个连接实例,如下所示:
- private void CreateJsonConnection()
- {
- _jsonConnection = new C1JsonConnection(_connBuilder.ConnectionString);
- }
复制代码
使用 SQL 查询数据- C1JsonDataAdapter adapter = new C1JsonDataAdapter(_jsonConnection, sql);
- var table = new DataTable();
- adapter.Fill(table);
复制代码
下面显示了一个示例平面数据和相应的查询:
- C1JsonDataAdapter adapter = new C1JsonDataAdapter(_jsonConnection, “select * from employees”);
- var table = new DataTable();
- adapter.Fill(table);
复制代码
对于关系数据,最终结果:
- C1JsonDataAdapter adapter = new C1JsonDataAdapter(_jsonConnection, (“Select FirstName, LastName, Amount from customers INNER JOIN Transactions ON customers._id = Transactions.customers_id where Transactions.IsSuccess=false”);
- var table = new DataTable();
- adapter.Fill(table);
复制代码
填充 DataTable 后,数据可以显示在网格中,如下所示:
在 Entity Framework Core 中使用 LINQ 查询 JSON
在本节中,我们将讨论如何在 Entity Framework Core 中使用 LINQ 查询 JSON 数据。我们从安装所需的 NuGet 包开始,即C1.EntityFrameworkCore.Json
安装 nuget 包后,接下来我们需要设置 DbContext 并提供到 JSON 数据源的连接字符串。为此,我们将使用C1JsonConnectionStringBuilder,如下所示:
- public abstract partial class DocumentContext : DbContext
- {
- private C1JsonConnectionStringBuilder _builder;
- public DocumentContext(C1JsonConnectionStringBuilder builder)
- {
- _builder = builder;
- Database.AutoTransactionsEnabled = false;
- }
- public DocumentContext(DbContextOptions<DocumentContext> options)
- : base(options)
- {
- Database.AutoTransactionsEnabled = false;
- }
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- if (!optionsBuilder.IsConfigured)
- {
- optionsBuilder.UseJson(_builder.ConnectionString);
- }
- }
- }
复制代码
如何创建 DbContext上面的DocumentContext类可以作为我们 JSON 文档的 DbContext 的基类。模型实体可以在子类中定义。
下面显示了平面 JSON 数据源的 DbContext 示例:
- public class EmployeesContext : DocumentContext
- {
- public virtual DbSet<Employee> Employees { get; set; }
- public EmployeesContext() : base(Utils.JsonConnectionBuilder) { }
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Employee>(entity =>
- {
- entity.ToTable("employees");
- entity.HasKey(x => x.Id);
- entity.Property(e => e.Id).HasColumnName("Id");
- entity.Property(e => e.FirstName).HasColumnName("FirstName");
- entity.Property(e => e.LastName).HasColumnName("LastName");
- entity.Property(e => e.Email).HasColumnName("Email");
- entity.Property(e => e.DOB).HasColumnName("DOB");
- entity.Property(e => e.Address).HasColumnName("Address");
- entity.Property(e => e.State).HasColumnName("State");
- entity.Property(e => e.Company).HasColumnName("Company");
- entity.Property(e => e.Gender).HasColumnName("Gender");
- entity.Property(e => e.JobTitle).HasColumnName("JobTitle");
- entity.Property(e => e.Skill).HasColumnName("Skill");
- entity.Property(e => e.Salary).HasColumnName("Salary");
- });
- }
- }
复制代码
下面显示了关系 JSON 数据源的 DbContext 示例:
- public class CustomersContext : DocumentContext
- {
- public virtual DbSet<Customer> Customers { get; set; }
- public virtual DbSet<Transaction> Transactions { get; set; }
- public CustomersContext() : base(Utils.CustomerDataConnectionStringBuilder) { }
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Transaction>(entity =>
- {
- entity.ToTable("Transactions");
- entity.HasOne(e => e.Customer).WithMany(x => x.Transactions).HasForeignKey("customers_id");
- entity.Property(e => e.Id).HasColumnName("_id");
- entity.Property(e => e.Amount).HasColumnName("Amount");
- entity.Property(e => e.Credited).HasColumnName("Credited");
- entity.Property(e => e.IsSuccess).HasColumnName("IsSuccess");
- entity.Property(e => e.Date).HasColumnName("Date");
- });
- modelBuilder.Entity<Customer>(entity =>
- {
- entity.ToTable("customers");
- entity.Property(e => e.Id).HasColumnName("_id");
- entity.Property(e => e.FirstName).HasColumnName("FirstName");
- entity.Property(e => e.LastName).HasColumnName("LastName");
- entity.Property(e => e.DOB).HasColumnName("DOB");
- entity.Property(e => e.State).HasColumnName("State");
- entity.Property(e => e.Gender).HasColumnName("Gender");
- });
- }
- }
复制代码
使用 LINQ 查询 DbContext既然设置了 DbContext,就可以使用 LINQ 查询 JSON 数据源。我们可以使用查询语法或方法语法:
- _context = new EmployeesContext();
- var employees = await _context.Employees.ToListAsync();
- // Employee count of companies starting with 'A'
- var employeeCountData = from employee in employees
- where employee.Company.StartsWith("A", StringComparison.OrdinalIgnoreCase)
- group employee by employee.Company into grp
- select new { Company = grp.Key, NumberOfEmployees = grp.Count() };
- // Salary growth of people working in Dynabox
- var salaryGrowthData = employees
- .Where(x => x.Company == "Dynabox").OrderBy(x => x.DOB)
- .Select(x => new { Age = DateTime.Now.Year - x.DOB.Year, Salary = x.Salary })
- .Where(x => x.Age >= 18)
- .GroupBy(x => x.Age)
- .Select(x => new { Age = x.Key, AverageSalary = x.Select(o => o.Salary).Average() });
复制代码
然后可以在网格/图表中使用数据,如下所示: