为 EF 代码第一个程序生成连接字符串

Generating connection string for EF code first program

我在 EF 中使用代码优先方法。第一次启动程序时需要根据用户输入生成连接字符串。

这是检查它现在是否可以连接的简单方法我正在尝试获取一些数据,因为碰巧在测试期间可以 open/close 连接但获取任何数据都会引发异常:

public static bool IsConnectionValid(string connectionString)
    {
        if (string.IsNullOrWhiteSpace(connectionString)) return false;
        using (var context = new HolidayCalendarContext(connectionString))
        {
            try
            {
                context.Database.Connection.Open();
                var contex = context.Employees.ToList();
                context.Database.Connection.Close();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }

现在我在这里生成连接字符串,用户名和密码是可选的,密码可能稍后作为参数提供:

private string GenerateConnectionString()
    {
        var builder = new SqlConnectionStringBuilder
        {
            DataSource = Source,
            InitialCatalog = Catalog,
            IntegratedSecurity = true,
            ConnectTimeout = CONNECTION_TIMEOUT
        };

        if (!string.IsNullOrWhiteSpace(UserName))
        {
            builder.UserID = UserName;
        }
        if (!string.IsNullOrWhiteSpace(Password))
        {
            builder.Password = Password;
        }
        return builder.ToString();
    }

我测试的方法是一个绑定到"Login to db"按钮的动作。 SaveConnection 只是将正确的连接字符串存储在配置文件中,而 ChangeUtility 只是此时不相关的导航内容。

private void LoginToDatabaseExecute(object obj)
    {
        if (ValidateInput())
        {
            var connectionString = GenerateConnectionString();
            if (TestConnection(connectionString))
            {
                SaveConnection(connectionString);
                ChangeUtility(new LoginViewModel(MainViewModel));
            }
        }
    }

所以我已经完成了生成这些字符串的测试,测试通过了。使用调试器检查,它正确连接并获取 Employees:

[TestMethod]
    public void SuccessfulConnectionStoresConnectionStringInSettings()
    {
        SetCorrectConnectionString();

        _viewModel.LoginToDatabaseCommand.Execute(null);

        var connectionString = SettingsHelper.GetConnectionString();

        Assert.IsFalse(string.IsNullOrWhiteSpace(connectionString));
    }

private void SetCorrectConnectionString()
    {
        _viewModel.Source = "YOGER\SQLEXPRESS";
        _viewModel.Catalog = "HolidayCalendar";
        _viewModel.UserName = "";
        _viewModel.Password = "";
    }

这就是问题所在。测试通过后,我启动程序,设置相同的输入,得到与测试 "Data Source=YOGER\SQLEXPRESS; Initial Catalog=HolidayCalendar; Integrated Security=True; Connect Timeout=5" 相同的 相同 连接字符串,但在 IsConnectionValid 尝试打开它时连接失败,抛出 "Keyword not supported: 'initial catalog'." System.ArgumentException

Exception thrown: 'System.ArgumentException' in System.Data.SqlServerCe.dll
Exception thrown: 'System.ArgumentException' in System.Data.dll

我已经尝试过 EntityConnectionStringBuilder 但它需要元数据,我发现代码首先没有元数据,所以我无法让它工作。

您正在尝试连接到 SQL Express,但是 SqlServerCe.dll 抛出了异常。它表明,您的程序使用 SQL CE 的提供程序。

我会检查您的 app.config` 文件中的 entityFramework.defaultConnectionFactory 部分。对于 SQL Express 应该设置为

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">

抛出异常:

'System.ArgumentException' in System.Data.SqlServerCe.dll

抛出异常:

'System.ArgumentException' in System.Data.dll

意味着直到你指出 SQL Server CE 数据库而不是 SQL Server Express