EntityFramework 是.NET平台非常优秀的一个ORM框架,经过多个版本的迭代,目前已经达到7.0版本,不过目前使用最普遍的还是6.0版本。EntitiyFramework使用LINQ来操作对象,EF内部将LINQ转化为SQL,然后对数据库执行CRUD操作。这个过程虽然简化了开发过程,但是由于从LINQ转化为SQL有性能损耗,所以EF的性能问题一直受人诟病。但EF也采取了一些措施来解决这些问题,其中一个方式就是CompileQuery(查询编译),值得注意的是,这里只是编译查询的条件,而不是结果,另外一种解决性能问题的方式就是缓存查询的结果,EF其实也提供了二级缓存来解决这个问题,后面的文章再讨论这个问题。
下面是一个使用CompileQuery的例子。
1.Model
namespace EFCompileQuery
{
using System;
using System.Collections.Generic;
public partial class Empoyees
{
public int Id { get; set; }
public string EmpoyeeName { get; set; }
public string Address { get; set; }
public string Email { get; set; }
}
}
2.ApplicationDbContext
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCompileQuery
{
class MyDbContext : ObjectContext
{
private static readonly Func<MyDbContext, string, IEnumerable<Empoyees>> EmpoyeeForCategoryCq = CompiledQuery.Compile(
(MyDbContext context, string employeeName) =>
from e in context.Empoyees where e.EmpoyeeName == employeeName select e
);
public MyDbContext(string connectionString)
: base(connectionString)
{
}
public MyDbContext()
: this("name=HibernateDBEntities")
{
}
public IEnumerable<Empoyees> GetEmpoyeesForCategory(string name)
{
return EmpoyeeForCategoryCq.Invoke(this, name).ToList();
}
public ObjectQuery<Empoyees> Empoyees {
get { return base.CreateObjectSet<Empoyees>(); }
}
}
}
3.App.config
<connectionStrings>
<add name="HibernateDBEntities"
connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;
provider=System.Data.SqlClient;provider connection string="data source=JUSTIN;
initial catalog=HibernateDB;integrated security=True;MultipleActiveResultSets=True;
App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
4.Test
using System;
using System.Data.Entity.Core.Objects;
using System.Linq;
namespace EFCompileQuery
{
class Program
{
static void Main(string[] args)
{
//Func<MyDbContext, string, IQueryable<Empoyees>> compiledQuery =
// CompiledQuery.Compile<MyDbContext, string, IQueryable<Empoyees>>(
// (db, name) => from e in db.Empoyees
// where e.EmpoyeeName == name
// select e);
var myDbContext = new MyDbContext();
var list = myDbContext.GetEmpoyeesForCategory("justin").ToList();
foreach (var e in list)
{
Console.WriteLine("Id: " + e.Id + ",Name: " + e.EmpoyeeName);
}
Console.ReadKey();
}
}
}
5.结果
6.总结:
EF在对性能要求不是很高的应用中使用还是十分合适的,也可以通过一些手段去规避性能问题,比如缓存等等。EF也在不断发展进步,今后一定会提供更多的机制来提升性能,让更多的开发者喜欢使用EF。
6.推荐
1)Entity Framework 学习高级篇—改善EF代码的方法
http://fhuan123.iteye.com/blog/1115082
2)预编译 LINQ 查询之CompiledQuery类及性能优化的介绍
http://www.cnblogs.com/wang726zq/archive/2012/04/19/compiledquery.html
3)MSDN Compile.Compile方法
https://technet.microsoft.com/zh-cn/library/system.data.linq.compiledquery.compile.aspx