使用 POCO 模板获取实体框架的连接字符串
我使用实体框架,我需要获取连接字符串,以便构建上下文。
我正在使用 POCO 模板。我的上下文对象有:
string ConnectionString = "name=MyAppConfigConnectionStringPropertyHere"
所以当我尝试构建我的上下文时它说
“在配置中找不到指定的命名连接,不适合与 EntityClient 提供程序一起使用,或者无效”
我在此 答案表明存在 GetConnectionString() 方法。但谷歌搜索并没有引导我找到我需要添加来获取该方法的参考(默认情况下它不在我的项目中)。
所以,我不能认为我是第一个想要使用 POCO 模板获取实体框架连接字符串的人。其他人是如何做到这一点的?我想我可以读取整个 app.config 文件并将其解析出来。但看起来应该没那么难。
任何提示都会很棒!
I use Entity Framework and I need to get my connection string so I can construct a context.
I am using the POCO template. My context object has:
string ConnectionString = "name=MyAppConfigConnectionStringPropertyHere"
So when I try to just construct my context it says
"The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid"
I saw in this answer that indicated that there is a GetConnectionString() method. But googling has not lead me to the reference I need to add to get that method (it is not in my project by default).
So, I can't think that I am the first one who wants to get a connection string for entity framework using the POCO templates. How have others done this? I guess I can just read in the whole app.config file and parse it out. But it seems like it should not be that hard.
Any hints would be great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于实体框架 6.0,以下代码给出当前的 ConnectionString。
For entity framework 6.0, following code gives current ConnectionString.
对于不使用 EF 4.1 的人,这是我所知道的最简单的方法:
For people not using EF 4.1 here is the easiest way to do it that I know of:
我像这样获得数据库连接
然后从连接中获得
ConnectionString
和您需要的其他信息I get the DB connection like this
Then from connection you get the
ConnectionString
and other info you need对于 EF Core,请使用:
For EF Core, use:
web.config 中必须存在一个在上下文中使用指定名称的 connectionString 元素:
There must be a connectionString-element present in the web.config that the specified name used on the context: