2013-12-13 74 views
1

我迁移到实体框架V6和我挣扎建立的代码,将让我定义的代码我的SQL 2008 R2数据库连接。由于这个库是多个应用程序将使用的dll,因此我无法在app.config文件中存储连接字符串信息。这个想法是维护1个DLL内的所有数据库连接,而不必在前端引用实体库,也不指定连接字符串。EF6应用程序代码

随着EF5我能够使用部分类,并定义在的DbContext连接字符串,这种方法似乎并不与EF6工作。我想要一个完全在代码中定义的EF6 SQL数据库连接的例子。大多数EF6的例子都是针对代码优先的模型,我已经有了数据库表,我只需要构建接口。

-Hiram

+0

为什么不能每个应用程序都有其自己的app.config文件? – Moho

+0

另外,你说你要保持你所提到的1个DLL中的所有数据库连接字符串或连接对象?请澄清。 – CokoBWare

+0

的情况是这样的: DLL维护所有连接到数据库。所有连接字符串等等。子应用程序只调用该DLL并将该DLL视为黑盒子。 随着目前的发展,当我引用的DLL与同一溶液(或不同的解决方案),另一个项目就抱怨说,没有连接字符串中找到。我认为将连接字符串编码到DLL本身可以消除这种混淆。 – hiramknick

回答

1

(假设你正在使用的EF设计器)

使用从EF6设计器生成的代码时,你不能只传递一个连接字符串的DbContext,因为需要的DbContext从创建的信息EDMX。但是您仍然可以创建一个具有接受连接字符串的构造函数的分部类。您只需创建一个ObjectContext并将其传递给DbContext构造函数。

下面是一个例子:

using System.Data.Entity.Core.EntityClient; 
using System.Data.Entity.Core.Metadata.Edm; 
using System.Data.Entity.Core.Objects; 
using System.Data.SqlClient; 

namespace Northwind.Model { 
    public partial class NorthwindEntities { 
     public NorthwindEntities(string connectionString) 
      : base(GetObjectContext(connectionString), true) { 
     } 

     private static ObjectContext GetObjectContext(string connectionString) { 
      // You can use the metadata portion of the connection string the the designer added to your config for the paths 
      var paths = new[] { 
       "res://*/Northwind.csdl", 
       "res://*/Northwind.ssdl", 
       "res://*/Northwind.msl" 
      }; 

      var workspace = new MetadataWorkspace(paths, new[] { typeof(NorthwindEntities).Assembly }); 
      var connection = new EntityConnection(workspace, new SqlConnection(connectionString)); 

      return new ObjectContext(connection); 
     } 
    } 
} 
1

您仍然可以定义在的DbContext在EF6的连接字符串。

public class ApplicationDbContext : DbContext 
{ 
    public ApplicationDbContext() 
     : base(@"Your connection string here") { } 

// Rest of your DbContext code 

} 

但是,在那里硬编码连接字符串并不是很通用。即使你DbContext将在它自己的DLL,它仍然可以读取主项目的app.configweb.config如果是在相同的解决方案(和我相当肯定它甚至会工作,如果你把你的DbContext DLL作为参考)。

只是在你DbContext项目添加到System.Configuration参考,然后你可以用任何ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionStringConfigurationManager.AppSettings["MyConnectionStringName"]

连接字符串得到你会在你的主要应用程序web.config连接字符串存储在<connectionStrings>段或在<appSettings>节“的app.config”

需要注意的是,如果你做这种方式(由web.configapp.config阅读),你应该相应地改变你的DbContext代码:

public class ApplicationDbContext : DbContext 
{ 
    public ApplicationDbContext() 
     : base("MyConnectionStringName") { } 

// Rest of your DbContext code 

}