遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

关于IDbConnectionFactory

需要EF4.0的DbContext

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Configuration;
using System.Data.SqlClient;
namespace F.Studio.Util.DB
{
    public  class MyDbContext :DbContext
    {
        static MyDbContext()
        {
            Database.SetInitializer<MyDbContext>(null);
            Database.DefaultConnectionFactory = new MyConnFactory();
        }
        /// <summary>
        /// 配置文件中的连接字符串名称
        /// </summary>
        /// <param name="name"></param>
        public MyDbContext(string nameOrConnStr)
            : base(nameOrConnStr)
        {
            
        }
        public MyDbContext()
            : base()
        {

        }
        

    }
    internal class MyConnFactory : IDbConnectionFactory
    {

        #region IDbConnectionFactory 成员

        public System.Data.Common.DbConnection CreateConnection(string nameOrConnectionString)
        {
            Console.WriteLine("连接工厂:" + nameOrConnectionString);
            return new SqlConnection("Data Source=192.168.1.7;Initial Catalog=JL_MFG;Persist Security Info=True;User ID=sa;Password=admin;Pooling=False");
            //传入的是连接字符串
            if (nameOrConnectionString.IndexOf("=") >= 0)
            {
                return new SqlConnection(nameOrConnectionString);
            }
            //到config文件的connections中找对应链接
            var connStr = ConfigurationManager.ConnectionStrings[nameOrConnectionString].ConnectionString;
            return new SqlConnection(connStr);
        }

        #endregion
    }
}
View Code

在设置了Database.DefaultConnectionFactory属性后,只有当配置文件中找不到指定的连接字符串时,才会使用ConnectionFactory来生成连接
搞半天发现不用这样方法

 

 

posted on 2013-06-01 16:32  遗忘海岸  阅读(1498)  评论(0编辑  收藏  举报