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>
效果: