如何在运行时设置EF码第一连接字符串

本文关键字:连接 字符串 EF 运行时 设置 | 更新日期: 2023-09-27 18:10:10

我错过了一些东西。我有一个小项目,我试图插入一些数据到数据库中。当我创建模型时,我对一个现有的数据库使用Code First。我想让应用程序能够在运行时指向任何服务器。这是一个下降和肮脏的实用程序和内部运行,但我需要一些灵活性时运行它。通过阅读一些msdn文章,我看到了可以在初始化时扩展DBContext的地方,因此我做了以下操作:

为初始化添加了一个参数:

 public OtherEventModel(string ConnectionString)
            : base("name=OtherEventModel")
        {...

然后在我的代码中,我基于从UI传入的属性构建了连接字符串:

private OtherEventModel ConnectToServer(string server, string username, string password)
        {
            try
            {
                SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
                {
                    DataSource =  server,
                    UserID = username,
                    Password = password,
                    InitialCatalog = "My_Database",
                    IntegratedSecurity = true
                };
                var connection = sqlBuilder.ToString();
                ModelContext = new OtherEventModel(connection);
                return ModelContext;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error connecting to server {0}", ex.Message));
            }

我可以看到创建的连接字符串,但是当我运行代码时,我收到一个异常,即连接字符串(应该在app.config中找不到)。因为我试图在运行时注入连接字符串,所以我在应用程序配置中没有连接字符串或键。

错误:

Error inserting data No connection string named 'OtherEventModel' could be found in the application config file

我从我读到的印象中,代码首先使用标准的SQL连接字符串,不需要EntityConnectionStringBuild(用于对象第一开发)

谁能给我指出正确的方向,我错过了什么或我做错了什么?

Thanks in advance

如何在运行时设置EF码第一连接字符串

差不多完成了,只需将连接字符串传递给base:

public OtherEventModel(string ConnectionString)
       : base(ConnectionString)

确保在下面的方法中注释了throw行。不幸的是,每次更新模型时都必须重新执行此操作。