C#如何更新实体模型连接字符串 [英] C# How To Update Entity Model Connection String

查看:82
本文介绍了C#如何更新实体模型连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用实体框架的第一个WinForm应用程序,我必须能够为即时创建的实体模型更新连接字符串,并且在我的app.config文件中,我具有以下connectionString:

This is my first WinForm application using the Entity Framework and I have to be able to update the connection string for the entity model I created on the fly and in my app.config file I have the following connectionString:

<add name="NCIPEntities" connectionString="metadata=res://*/NCIPModel.csdl|res://*/NCIPModel.ssdl|res://*/NCIPModel.msl;provider=System.Data.SQLite;provider connection string='data source=&quot;C:\Test\NCIP\NCIP.db3&quot;;pooling=True'" providerName="System.Data.EntityClient" />

这是我写来动态更新字符串的内容,当

This is what I wrote to update the string on the fly, it doesn't throw any errors when it runs but it also doesn't save the new connection string back to the app.config file.

private void UpdateEntityConnection()
    {
        StringBuilder Sb = new StringBuilder();
        Sb.Append(@"metadata=res://*/NCIPModel.csdl|res://*/NCIPModel.ssdl|res://*/NCIPModel.msl;provider=System.Data.SQLite;provider""");
        Sb.Append("connection string='data source=" + Settings.Default.Directory + "\\NCIP.db3;pooling=True'");

        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.ConnectionStrings.ConnectionStrings["NCIPEntities"].ConnectionString = Sb.ToString();

        config.Save(ConfigurationSaveMode.Minimal);
        ConfigurationManager.RefreshSection("connectionStrings");
    }

有人看见我在做什么错是因为我没有这样做。

Does anyone see what I am doing wrong because I don't.

谢谢。

推荐答案

您知道可以这样做吗?

Did you know you can do this:

var connstr = GetConnectionString();

using (NCIPEntities ctx = new NCIPEntities(connstr))
{
    ...
}

无论如何,知道这可能会稍微改变您的方法/要求吗?

Anyway knowing this might change your approach/requirements a little?

希望这会有所帮助

Alex

PS:您可能想要查看我的提示45 了解更多信息。
我有一个整个系列提示

PS: you might want to check out my Tip 45 for more info. I have a whole series of Tips too

这篇关于C#如何更新实体模型连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆