EF Core中如何取消跟踪DbContext中所有被跟踪的实体

时间:2023-03-10 02:18:18
EF Core中如何取消跟踪DbContext中所有被跟踪的实体

首先定义一个DbContext的扩展类DbContextDetachAllExtension,其中包含一个DbContext的扩展方法DetachAll,用来取消跟踪DbContext中所有被跟踪的实体:

using Microsoft.EntityFrameworkCore;
using System.Linq; namespace DbContextUtils
{
/// <summary>
/// DbContext的扩展类
/// </summary>
public static class DbContextDetachAllExtension
{
/// <summary>
/// 取消跟踪DbContext中所有被跟踪的实体
/// </summary>
public static void DetachAll(this DbContext dbContext)
{
//循环遍历DbContext中所有被跟踪的实体
while (true)
{
//每次循环获取DbContext中一个被跟踪的实体
var currentEntry = dbContext.ChangeTracker.Entries().FirstOrDefault(); //currentEntry不为null,就将其State设置为EntityState.Detached,即取消跟踪该实体
if (currentEntry != null)
{
//设置实体State为EntityState.Detached,取消跟踪该实体,之后dbContext.ChangeTracker.Entries().Count()的值会减1
currentEntry.State = EntityState.Detached;
}
//currentEntry为null,表示DbContext中已经没有被跟踪的实体了,则跳出循环
else
{
break;
}
}
}
}
}

其用法如下:

using ConsoleApp1.Entities;
using DbContextUtils;
using System;
using System.Linq; namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (DemoContext dbContext = new DemoContext())
{
var Persons = dbContext.Person.ToList(); dbContext.DetachAll();
} Console.WriteLine("Press key..");
Console.ReadKey(); }
}
}