• Stars
    star
    511
  • Rank 86,473 (Top 2 %)
  • Language
    C#
  • License
    GNU General Publi...
  • Created about 4 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Deleting or Updating multiple records from a LINQ Query in a SQL statement without loading entities

.NET 7 and above users, please check this

Zack.EFCore.Batch

中文文档 Chinese version

Using this library, Entity Framework Core users can delete or update multiple records from a LINQ Query in a SQL statement without loading entities. This libary supports Entity Framework Core 5.0 and Entity Framework Core 6.0.

Instructions:

Step 1

As for.NET 5 users:

SQLServer: Install-Package Zack.EFCore.Batch.MSSQL
MySQL: Install-Package Zack.EFCore.Batch.MySQL.Pomelo
Postgresql: Install-Package Zack.EFCore.Batch.Npgsql
Sqlite: Install-Package Zack.EFCore.Batch.Sqlite
Oracle:Install-Package Zack.EFCore.Batch.Oracle
Dm(达梦): Install-Package ZackEFCore.Batch.Dm
In Memory:Install-Package Zack.EFCore.Batch.InMemory

As For.NET 6 users:

SQLServer: Install-Package Zack.EFCore.Batch.MSSQL_NET6
MySQL: Install-Package Zack.EFCore.Batch.MySQL.Pomelo_NET6
Postgresql: Install-Package Zack.EFCore.Batch.Npgsql_NET6
Sqlite: Install-Package Zack.EFCore.Batch.Sqlite_NET6
Oracle: Install-Package Zack.EFCore.Batch.Oracle_NET6
In Memory:Install-Package Zack.EFCore.Batch.InMemory_NET6

Support of MySQL is based on Pomelo.EntityFrameworkCore.MySql.

Step 2:

Depending on the database, add the following code into OnConfiguring() method of your DbContext respectively.

optionsBuilder.UseBatchEF_MSSQL();// as for MSSQL Server
optionsBuilder.UseBatchEF_Npgsql();//as for Postgresql
optionsBuilder.UseBatchEF_MySQLPomelo();//as for MySQL
optionsBuilder.UseBatchEF_Sqlite();//as for Sqlite
optionsBuilder.UseBatchEF_Oracle();//as for Oracle
optionsBuilder.UseBatchEF_DM();//as for DM(达梦)
optionsBuilder.UseBatchEF_InMemory();//as for In Memory
Step 3:

Use the extension method DeleteRangeAsync() of DbContext to delete a set of records. The parameter of DeleteRangeAsync() is the lambda expression of the filter Example code:

await ctx.DeleteRangeAsync<Book>(b => b.Price > n || b.AuthorName == "zack yang"); 

The code above will execute the following SQL statement on database:

Delete FROM [T_Books] WHERE ([Price] > @__p_0) OR ([AuthorName] = @__s_1)

and the DeleteRange() is the synchronous version of DeleteRangeAsync().

Use the extension method BatchUpdate() of DbContext to create a BatchUpdateBuilder. There are four methods in BatchUpdateBuilder as follows

  • Set() is used for assigning a value to a property. The first parameter of the method is the lambda expression of the property, and the second one is the lambda expression of the value.
  • Where() is used for setting the filter expression
  • ExecuteAsync() is an asynchronous method that can execute the BatchUpdateBuilder, and the Execute() is a synchronous alternative of ExecuteAsync()

Example code:

await ctx.BatchUpdate<Book>()
    .Set(b => b.Price, b => b.Price + 3)
    .Set(b => b.Title, b => s)
    .Set(b => b.AuthorName,b=>b.Title.Substring(3,2)+b.AuthorName.ToUpper())
    .Set(b => b.PubTime, DateTime.Now)
    .Where(b => b.Id > n || b.AuthorName.StartsWith("Zack"))
    .ExecuteAsync();

The code above will execute the following SQL statement on database:

Update [T_Books] SET [Price] = [Price] + 3.0E0, [Title] = @__s_1, [AuthorName] = COALESCE(SUBSTRING([Title], 3 + 1, 2), N'') + COALESCE(UPPER([AuthorName]), N''), [PubTime] = GETDATE()
WHERE ([Id] > @__p_0) OR ([AuthorName] IS NOT NULL AND ([AuthorName] LIKE N'Zack%'))

Take(), Skip()

Take() and Skip() can be used to limit the affected rows of DeleteRangeAsync and BatchUpdate:

await ctx.Comments.Where(c => c.Article.Id == id).OrderBy(c => c.Message)
.Skip(3).DeleteRangeAsync<Comment>(ctx);
await ctx.Comments.Where(c => c.Article.Id == id).Skip(3).Take(10).DeleteRangeAsync<Comment>(ctx);
await ctx.Comments.Where(c => c.Article.Id == id).Take(10).DeleteRangeAsync<Comment>(ctx);

await ctx.BatchUpdate<Comment>().Set(c => c.Message, c => c.Message + "abc")
	.Where(c => c.Article.Id == id)
	.Skip(3)
	.ExecuteAsync();

await ctx.BatchUpdate<Comment>()
	.Set(c => c.Message, c => "abc")
	.Where(c => c.Article.Id == id)
	.ExecuteAsync();
	
await ctx.BatchUpdate<Comment>()
	.Set("Message","abc")
	.Where(c => c.Article.Id == id)
	.ExecuteAsync();

await ctx.BatchUpdate<Comment>().Set(c => c.Message, c => c.Message + "abc")
	.Where(c => c.Article.Id == id)
	.Skip(3)
	.Take(10)
	.ExecuteAsync();
await ctx.BatchUpdate<Comment>().Set(c => c.Message, c => c.Message + "abc")
   .Where(c => c.Article.Id == id)
   .Take(10)
   .ExecuteAsync();

BulkInsert

At this point, BulkInsert cannot be supported on SqlLite.

List<Book> books = new List<Book>();
for (int i = 0; i < 100; i++)
{
	books.Add(new Book { AuthorName = "abc" + i, Price = new Random().NextDouble(), PubTime = DateTime.Now, Title = Guid.NewGuid().ToString() });
}
using (TestDbContext ctx = new TestDbContext())
{
	ctx.BulkInsert(books);
}

On mysql, to use BulkInsert, please enable local_infile on server side and client side: enable "local_infile=ON" on mysql server, and add "AllowLoadLocalInfile=true" to connection string on client side.

Misc

This library utilizes the EF Core to translate the lambda expression to SQL statement, so it supports nearly all the lambda expressions which EF Core supports.

The following databases have been tested that they can work well with Zack.EFCore.Batch: MS SQLServer(Microsoft.EntityFrameworkCore.SqlServer), MySQL(Pomelo.EntityFrameworkCore.MySql), PostgreSQL(Npgsql.EntityFrameworkCore.PostgreSQL), Oracle(Oracle.EntityFrameworkCore). In theory, as long as a database has its EF Core 5/6 Provider , the database can be supported by this library. If you are using a database that is not currently supported, please submit an issue. I can usually complete the development within one working day.

Report of this library

More Repositories

1

NETBookMaterials

C#
533
star
2

Zack.DotNetTrimmer

C#
316
star
3

yzk18

Java libraries for beginners. It can simplify the use of Java in the field of office automation.
Java
100
star
4

Zack.AnyDBConfigProvider

ConfigurationProvider for loading configuration from any database, including but not limited to SQLServer, MySQL, Oracle, etc.
C#
89
star
5

RuPengMessageHub

.Net Chat Server Hub
JavaScript
86
star
6

Zack.OpenCVSharp.Ext

It is an extension library of OpenCvSharp. It provides ResourceTracker, which can facilitate the resources management of Mat and other unmanaged resources. It also provide a class, named np, which is a managed version of Numpy.
C#
67
star
7

RuPeng.HystrixCore

C#
48
star
8

RuPeng.RestTemplateCore

C#
32
star
9

LessCode.EFCore.StronglyTypedId

Automatically generate Types for Strongly Typed Id in Entity Framework Core
C#
30
star
10

cownewsql

Sql dialect translator
Java
20
star
11

PhoneAsPrompter

Use for your as a free teleprompter, which can connect to PowerPoint.
C#
19
star
12

YouZack.FromJsonBody

Bind simple parameter of Action with HttpBody of Json format. For ASP.Net Core MVC and ASP.Net Core WebAPI
C#
18
star
13

ApplyMasksForWorldCup

C#
16
star
14

WebCSC

A library that can compile and run C# code in the browser.
C#
16
star
15

CaptchaGen.NetCore

Captcha generator for .net core
C#
15
star
16

MDictExtractor

Extract data from MDict mdd mdx file,like mdict parser
C#
14
star
17

2021NETConf_SourceGenerator

C#
13
star
18

UpYun.NETCore

又拍云 SDK .net Core版
C#
13
star
19

NAHA

NAHA-A python console UI Library that wrapped PyCurses
Python
12
star
20

Zack.TuyaNet

C#
10
star
21

ZackData.Net

A wrapper of EntityFramework/EntityFramework Core, which is like Spring Data JPA
C#
8
star
22

Zack.CameraLib

List connected cameras. CameraPlayer.
C#
8
star
23

XimalayaDownloader

自动化下载喜马拉雅的音频
C#
7
star
24

Microsoft.AspNetCore.Identity.zh-Hans

Chinese version of IdentityError of asp.net core identity. 此程序包包含 ASP.NET Core Identity 的简体中文附属程序集。
C#
7
star
25

rongim.server.netcore

融云ServerSDK .Net Core版
C#
6
star
26

NetAutoGUI

.NET version of pyAutoGUI
C#
6
star
27

BiLiBiLiPaiLou

给B站评论排楼号
JavaScript
6
star
28

uniapp-youzack-components

youzack的UniApp的组件
Vue
5
star
29

GTK4J

Java binding for GTK
Java
5
star
30

Zack.ComObjectHelpers

Utilities for simplifying the operations on ComObject of .NET5.
C#
5
star
31

Windows-Phone-Emulator

C#
5
star
32

Zack.Weixin.MiniProgram

微信小程序服务器端API的.NET版,.NET Standard 2.0。不像Senparc那么复杂
C#
5
star
33

programming_vocabulary

4
star
34

RuPengStudy-NetIM

A Chat window client
JavaScript
4
star
35

NAHAIDE

Java
3
star
36

SweetHeartPlayer

Just for fun
JavaScript
3
star
37

RuPeng.Common.NetCore

Common .net library of Rupeng.Com
C#
3
star
38

YouZack.ErrorMail

Mail Logging provider on .Net Core, which can be configured as 'send the same error only once'
C#
2
star
39

aliyun_yunkaifapingtai_demo

阿里云云开发平台演示案例
Java
2
star
40

Zack.IoT.NET

Python
2
star
41

YZKGame.NET

YZKGame 2D game engine
C#
2
star
42

yzk18.com

sourcecode of yzk18.com websites
HTML
2
star
43

ZackOLEContainer

C#
2
star
44

misc

misc
C
1
star