您仍然可以定义在的DbContext在EF6的连接字符串。
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
: base(@"Your connection string here") { }
// Rest of your DbContext code
}
但是,在那里硬编码连接字符串并不是很通用。即使你DbContext
将在它自己的DLL,它仍然可以读取主项目的app.config
或web.config
如果是在相同的解决方案(和我相当肯定它甚至会工作,如果你把你的DbContext
DLL作为参考)。
只是在你DbContext
项目添加到System.Configuration
参考,然后你可以用任何ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString
或ConfigurationManager.AppSettings["MyConnectionStringName"]
连接字符串得到你会在你的主要应用程序web.config
连接字符串存储在<connectionStrings>
段或在<appSettings>
节“的app.config”
需要注意的是,如果你做这种方式(由web.config
或app.config
阅读),你应该相应地改变你的DbContext
代码:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
: base("MyConnectionStringName") { }
// Rest of your DbContext code
}
为什么不能每个应用程序都有其自己的app.config文件? – Moho
另外,你说你要保持你所提到的1个DLL中的所有数据库连接字符串或连接对象?请澄清。 – CokoBWare
的情况是这样的: DLL维护所有连接到数据库。所有连接字符串等等。子应用程序只调用该DLL并将该DLL视为黑盒子。 随着目前的发展,当我引用的DLL与同一溶液(或不同的解决方案),另一个项目就抱怨说,没有连接字符串中找到。我认为将连接字符串编码到DLL本身可以消除这种混淆。 – hiramknick