EF中DataContext创建的两段代码收藏

ExpandedBlockStart.gifDataContextAutoDisposeModule
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Collections;
 6 using System.Data.Linq;
 7 
 8 /// <summary>
 9 /// 实现自动抛弃当前数据库上下文的模块。
10 /// </summary>
11 public sealed class DataContextAutoDisposeModule : IHttpModule
12 {
13     #region IHttpModule 成员
14     public void Init(HttpApplication context)
15     {
16         context.PostRequestHandlerExecute += new EventHandler(Enter);
17     }
18 
19     public void Dispose()
20     {
21     }
22     #endregion
23 
24     private void Enter(object sender, EventArgs e)
25     {
26         IDictionary httpContextItems = HttpContext.Current.Items;
27         List<object> keys = new List<object>(httpContextItems.Count);
28 
29         foreach (DictionaryEntry item in httpContextItems)
30         {
31             DataContext dataContext = item.Value as DataContext;
32             if (dataContext != null)
33             {
34                 dataContext.Dispose();
35                 keys.Add(item.Key);
36             }
37         }
38 
39         foreach (object key in keys)
40         {
41             httpContextItems.Remove(key);
42         }
43     }
44 }
ExpandedBlockStart.gifDataContextFactory
using System.Data.Linq;
using System.Web;

public static class DataContextFactory
{
    
public static TDataContext GetDataContext<TDataContext>()
        
where TDataContext : DataContext, new()
    {
        
if (HttpContext.Current != null)
        {
            
string key = typeof(TDataContext).FullName;

            TDataContext dataContext 
= HttpContext.Current.Items[key] as TDataContext;
            
if (dataContext == null)
            {
                dataContext 
= new TDataContext();
                HttpContext.Current.Items[key] 
= dataContext;
            }
            
return dataContext;
        }

        
return new TDataContext();
    }
}

转载于:https://www.cnblogs.com/brusehht/archive/2011/09/09/2172494.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值