Entity Framework的性能优化:
1.使用
MergeOption
.
NoTracking
(发现添加这个代码后, 导致"The object cannot be deleted because it was not found in the ObjectStateManager."错误,解决办法为, 先调用entity实例的Attach(
deleteObj),参数为要删除的对象,然后调用
ObjectStateManager.ChangeObjectState(deleteObj, EntityState.Deleted),具体参考
http://www.cnblogs.com/Benjamin/archive/2012/10/24/2736739.html
)
在EF生成的ObjectContext的构造里设置MergeOption, 如:
public partial class protocoldbEntities : ObjectContext { #region Constructors /// <summary> /// Initializes a new protocoldbEntities object using the connection string found in the 'protocoldbEntities' section of the application configuration file. /// </summary> public protocoldbEntities() : base("name=protocoldbEntities", "protocoldbEntities") { this.protocolnodes.MergeOption = MergeOption.NoTracking; this.protocolversionhistories.MergeOption = MergeOption.NoTracking;this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); }
2. 使用IQueryable和Compiled Queries
如: 定义一个Func变量, CompiledQuery.Compile中传入entity对象,查询结果,以及可选的查询条件 。此例中,protocolDB是entity, 包含protocolnodes表,
//
private static Func<protocoldbEntities, string, protocolnode> _protocolNodeByUIDQueryFunc;
//
if (null == _protocolNodeByUIDQueryFunc)
{ _protocolNodeByUIDQueryFunc = CompiledQuery.Compile<protocoldbEntities, string, protocolnode>((ctx, uid) => ctx.protocolnodes.FirstOrDefault(p => p.ProtocolNodeUID == uid) ); } protocolnode temp = _protocolNodeByUIDQueryFunc.Invoke(protocolDB, UID);
protocolDB.Refresh(RefreshMode.StoreWins, temp);//必须调用, 这样查询的数据才是数据库最新的,不然会出现数据库获取的数据是旧的。
3. 创建视图
http://blogs.msdn.com/b/adonet/archive/2008/06/20/how-to-use-a-t4-template-for-view-generation.aspx
http://www.asp.net/web-forms/tutorials/continuing-with-ef/maximizing-performance-with-the-entity-framework-in-an-asp-net-web-application