zoukankan      html  css  js  c++  java
  • 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();
    
            }
        }
    }
  • 相关阅读:
    第十八章、使用集合
    第十九章、枚举集合
    第十七章、泛型概述
    第十六章、使用索引器
    第十五章、实现属性以访问字段
    第十四章、使用垃圾回收和资源管理
    第十三章、创建接口和定义抽象类
    AtCoder Grand Contest 018 E
    AtCoder Regular Contest 059 F Unhappy Hacking
    Codeforces 464E. The Classic Problem
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/10217772.html
Copyright © 2011-2022 走看看