优化EF的性能

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值