当前位置:网站首页>Efcore tuning
Efcore tuning
2022-06-12 19:40:00 【Rodinia lava】
Initialization data :
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreDemon1
{
internal class MyDbContext:DbContext
{
public DbSet<Article> Articles {
get; set; } //API The name of
public DbSet<Comment> Comments {
get; set; }
public DbSet<Comment2> Comment2s {
get; set; }
public DbSet<Customers> Customers {
get; set; } //API The name of
public DbSet<Orders> Orders {
get; set; }
private ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
//Microsoft.Extensions.Configuration.JsonConfigurationExtensions
cfgBuilder.AddJsonFile("DbCfg.json", optional: true, reloadOnChange: true);
IConfigurationRoot configRoot = cfgBuilder.Build();
string connString = configRoot.GetSection("ConnectionStrings:SqliteConnectionString").Value;
optionsBuilder.UseSqlite(connString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customers>()
.HasData
(
new Customers {
Id = 1, Name = "Joe" },
new Customers {
Id = 2, Name = "Henry" },
new Customers {
Id = 3, Name = "Sam" },
new Customers {
Id = 4, Name = "Max" }
);
modelBuilder.Entity<Orders>()
.HasData
(
new Orders {
Id = 1, Name = "DDD", CustomerId = 3, CustomerId2 = 3 },
new Orders {
Id = 2, Name = "EEE", CustomerId = 1, CustomerId2 = 1 },
new Orders {
Id = 3, Name = "FFF", CustomerId = 2 },
new Orders {
Id = 4, Name = "GGG", CustomerId = 4 }
);
modelBuilder.Entity<Comment2>()
.HasData
(
new Comment2 {
Id = 1, Message = "Orders1 The comments ", OrdersId = 1 },
new Comment2 {
Id = 2, Message = "Orders1 The comments ", OrdersId = 1 },
new Comment2 {
Id = 3, Message = "Orders2 The comments ", OrdersId = 2 },
new Comment2 {
Id = 4, Message = "Orders2 The comments ", OrdersId = 2 },
new Comment2 {
Id = 5, Message = "Orders3 The comments ", OrdersId = 3 },
new Comment2 {
Id = 6, Message = "Orders3 The comments ", OrdersId = 3 },
new Comment2 {
Id = 7, Message = "Orders3 The comments ", OrdersId = 3 },
new Comment2 {
Id = 8, Message = "Orders4 The comments ", OrdersId = 4 }
);
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
}
}
json To configure
{
"ConnectionStrings": {
"SqliteConnectionString": "Data Source=D:\\Db\\DbSqlite.db",
"MySQLConnectionString": "server=127.0.0.1; database=OneToMany; uid=root; pwd=123456;"
}
}
result :
// See https://aka.ms/new-console-template for more information
global using EFCoreDemon1;
global using EFCoreDemon1.Entities;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System.Data.Common;
// A website contains two tables ,Customers Table and Orders surface . Write a SQL Inquire about , Find all customers who never order anything .
using MyDbContext myDb = new MyDbContext();
var customers = myDb.Orders.Where(o=>o.CustomerId2 == null).Select(o=>o.Customers);
// for the first time Select Point to a collection through a foreign key , From entering Orders The other table Customers, the second select Use select Select the specified field
var name = myDb.Orders.Where(o => o.CustomerId2 == null).Select(o => o.Customers).Select(c => c.Name);
// for the first time Select Point to a collection through a foreign key , from Customers Enter another table Orders, the second select, from Orders Enter table Comment2
var test = myDb.Customers.Where(c => c.Id > 1).Select(c => c.Orders).Where(o => o.Name == "DDD").Select(o => o.Comment2s);
//var a = myDb.Customers.FromSqlInterpolated($"Select * from Orders").ToList();
//myDb.Orders.FromSqlInterpolated($"Select Name From Customers where Customers.Id not in ()")
foreach (var item in customers)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("=======================");
foreach (var item in name)
{
Console.WriteLine(item);
}
Console.WriteLine("=======================");
// The relationship between the last two tables is one to many , Must be cycled twice
foreach (var item in test)
{
foreach (var i in item)
{
Console.WriteLine(i.Message);
}
}
/* result Henry Max ======================= Henry Max ======================= Orders1 The comments Orders1 The comments */
// Write primitive AdoNetCore
Console.WriteLine("=======================");
DbConnection conn = myDb.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
{
await conn.OpenAsync();
}
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "select Customers.name from Customers where Customers.Id in (select CustomerId2 from Orders)";
using(var reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var test1 = reader.GetValue(0);
Console.WriteLine(test1);
}
}
}
/* result : Joe Sam */
Entity class and configuration :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreDemon1.Entities
{
public class Customers
{
public int Id {
get; set; }
public string Name {
get; set; }
public Orders Orders {
get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreDemon1.Entities
{
public class Orders
{
public int Id {
get; set; }
public string Name {
get; set; }
public Customers Customers {
get; set; }
public int CustomerId {
get; set; }
public int? CustomerId2 {
get; set; }
public List<Comment2> Comment2s {
get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreDemon1.Entities
{
public class Comment2
{
public int Id {
get; set; }
public Orders Orders {
get; set; }
public int OrdersId {
get; set; } // Foreign keys
public string Message {
get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreDemon1.Db
{
public class CustomersConfig : IEntityTypeConfiguration<Customers>
{
public void Configure(EntityTypeBuilder<Customers> builder)
{
builder.ToTable("Customers");
builder.HasKey(c => c.Id); // Set primary key
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreDemon1.Db
{
public class OrdersConfig : IEntityTypeConfiguration<Orders>
{
public void Configure(EntityTypeBuilder<Orders> builder)
{
builder.ToTable("Orders");
builder.HasKey(a => a.Id); // Set primary key
builder.HasOne<Customers>(o => o.Customers)
.WithOne(c => c.Orders).HasForeignKey<Orders>(o => o.CustomerId);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreDemon1.Db
{
public class Comment2Config : IEntityTypeConfiguration<Comment2>
{
public void Configure(EntityTypeBuilder<Comment2> builder)
{
builder.ToTable("Comment2");
builder.HasKey(a => a.Id); // Set primary key
builder.HasOne<Orders>(c => c.Orders)
.WithMany(o => o.Comment2s)
.HasForeignKey(o => o.OrdersId);
}
}
}
边栏推荐
- Shell 数组和函数
- Equipment management - borrowing / returning module interface code
- Details of thansmitablethreadlocal
- 7:00 tonight | application of PhD debate self supervised learning in Recommendation System
- 【刷题笔记】线段树
- Global and Chinese smart government industry market research and investment risk outlook report 2022-2028
- How do I create my own appender in log4j- How to create my own Appender in log4j?
- 负数取余问题
- China's asset management market demand and future competitive trends outlook report 2022-2028
- Reasonably configure thread pool
猜你喜欢
Negative remainder problem
Reading applet based on wechat e-book graduation design (2) applet function
【生成对抗网络学习 其三】BiGAN论文阅读笔记及其原理理解
开源深度学习框架PlaidML安装及测试
什么是数据驱动
5g R17 standard is frozen. What does it say?
基于微信电子书阅读小程序毕业设计毕设作品(7)中期检查报告
Detailed explanation of IO flow basic knowledge -- file and IO flow principle
"As a service", the future has come, starting from the present | new mode of it consumption, FOD billing on demand
BigTable (II): how BigTable achieves scalability and high performance
随机推荐
Cookie & Session & kaptcha驗證碼
Implementation of VGA protocol based on FPGA
Reasonably configure thread pool
Demand and business model innovation - demand 1 - Introduction to demand engineering
Transactions in redis
【生成对抗网络学习 其三】BiGAN论文阅读笔记及其原理理解
QT -- how to get the contents of selected cells in qtableview
Equipment management - borrowing and returning module 1
PostgreSQL数据库复制——后台一等公民进程WalReceiver pg_stat_wal_receiver视图
Reading small programs based on wechat e-book graduation design works (7) Interim inspection report
EASYCODE one click plug-in custom template
[SQL] MySQL query statement execution sequence analysis
Research Report on current market situation and investment prospect of China's tobacco RFID industry 2022-2027
94. 解析网页中的内容
Hardware test - why not use grounding clip for ripple test
Demand and business model innovation - demand 3- demand engineering process
asp. Net using JSON to interact with API data
Demand and business model innovation - demand 2- demand basis
Reading applet based on wechat e-book graduation design (2) applet function
review.js ppt数学公式无法显示