EF Data Operation With Async Task

本文展示了一个使用Entity Framework进行异步数据操作的例子,包括添加数据及查询操作,并附带完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

EF的性能问题一直受人诟病,其实EF通过异步操作在一定程度了缓解了性能问题,同时EF支持二级缓存,这两种方式都为提高EF的性能提供了帮助。今天写了一个异步的例子,代码如下,仅供参考!

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EFAsync
{
    class Program
    {
        static void Main(string[] args)
        {
            var task = AsycOperation();
            task.Wait();
            Console.ReadKey();
        }

        private static async Task AsycOperation()
        {
            using (var ctx = new ApplicationDbContext())
            {
                Console.WriteLine("准备添加数据,当前线程Id为{0}", 
                    Thread.CurrentThread.ManagedThreadId);
                ctx.Empoyees.Add(new Empoyee()
                {
                    EmpoyeeName = "justin",
                    Address = "shanghai",
                    Email = "justinfu@wicresoft.com"
                });

                await ctx.SaveChangesAsync();

                Console.WriteLine("数据保存完成,当前线程Id为{0}", 
                    Thread.CurrentThread.ManagedThreadId);

                Console.WriteLine("开始执行查询,当前线程Id为{0}", 
                    Thread.CurrentThread.ManagedThreadId);

                var employees = await (from employee 
                                           in ctx.Empoyees 
                                       select employee).ToListAsync();

                Console.WriteLine("遍历获得所有学生的姓名,当前线程Id为{0}", 
                    Thread.CurrentThread.ManagedThreadId);

                foreach (var e in employees)
                {
                    Console.WriteLine("学生姓名为:{0}", e.EmpoyeeName);
                }
            }
        }
    }
}


ApplicationDbContext

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFAsync
{
    class ApplicationDbContext:DbContext
    {
        public ApplicationDbContext()
            :base("name=ModelsContainer")
        {
            
        }

        public DbSet<Empoyee> Empoyees { get; set; }
    }
}
Employee

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFAsync
{
    class Empoyee
    {
        public int Id { set; get; }

        public string EmpoyeeName { set; get; }

        public string Address { set; get; }

        public string Email { set; get; }
    }
}
App.config

 <connectionStrings>
    <add name="ModelsContainer" 
         connectionString="Data Source=(local);Database=HibernateDB;User ID=sa; Password=1234;"
         providerName="System.Data.SqlClient"/>
 </connectionStrings>
效果:






应用程序: Asd.AgingTestRack.IMP.SunnyUI.WinAPP.exe Framework 版本: v4.0.30319 说明: 由于未经处理的异常,进程终止。 异常信息: System.Data.SQLite.SQLiteException 在 System.Data.SQLite.SQLite3.Prepare(System.Data.SQLite.SQLiteConnection, System.Data.SQLite.SQLiteCommand, System.String, System.Data.SQLite.SQLiteStatement, UInt32, System.String ByRef) 在 System.Data.SQLite.SQLiteCommand.BuildNextCommand() 在 System.Data.SQLite.SQLiteCommand.GetStatement(Int32) 在 System.Data.SQLite.SQLiteDataReader.NextResult() 在 System.Data.SQLite.SQLiteDataReader..ctor(System.Data.SQLite.SQLiteCommand, System.Data.CommandBehavior) 在 System.Data.SQLite.SQLiteCommand.ExecuteReader(System.Data.CommandBehavior) 在 System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(System.Data.CommandBehavior) 在 System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(System.Data.CommandBehavior, System.Threading.CancellationToken) 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition+<ExecuteStoreCommandsAsync>d__26.MoveNext() 异常信息: System.Data.Entity.Core.EntityCommandExecutionException 在 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition+<ExecuteStoreCommandsAsync>d__26.MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan+<ExecuteAsync>d__10`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResult() 在 System.Data.Entity.Core.Objects.ObjectContext+<ExecuteInTransactionAsync>d__156`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResult() 在 System.Data.Entity.Core.Objects.ObjectQuery`1+<GetResultsAsync>d__43[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResult() 在 System.Data.Entity.Internal.LazyAsyncEnumerator`1+<FirstMoveNextAsync>d__9[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions+<SingleOrDefaultAsync>d__31`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResult() 在 System.Data.Entity.Internal.Linq.InternalSet`1+<FindInStoreAsync>d__12[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Data.Entity.Internal.Linq.InternalSet`1+<FindInternalAsync>d__9[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResult() 在 Asd.AgingTestRack.IMP.DB.DAO.HistoryDataDao+<AddOrUpdateHistoryDataAsync>d__1`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.GetResult() 在 Asd.AgingTestRack.IMP.DB.DAO.HistoryDataDao+<Addr4>d__5.MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 在 System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(System.Threading.Tasks.Task) 在 Asd.AgingTestRack.IMP.SunnyUI.WinAPP.FrmRunPlant+<ChangeAgItemStatus2>d__53.MoveNext() 在 System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_1(System.Object) 在 System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object) 在 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) 在 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) 在 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() 在 System.Threading.ThreadPoolWorkQueue.Dispatch() 在 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() 分析报错原因
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值