c# - 无法打开数据库,未创建数据库

标签 c# sql-server entity-framework

我想使用 Entity Framework 从我的代码创建一个数据库。数据库服务器是 Window Server 2012 数据中心上的 MS SQL 2012 BI。

我尝试使用 MSDN 中的示例来执行此操作。我的配置如下所示:

  <defaultConnectionFactory
        type="System.Data.Entity.Infrastructure.SqlConnectionFactory, 
            EntityFramework">
      <parameters>
        <parameter value="Data Source=databaseserver;User Id=name;Password=password; MultipleActiveResultSets=True " />
      </parameters>
    </defaultConnectionFactory>

我收到一个带有“用户 xy 登录时出错”、“无法打开数据库”的 SqlException。这很明显,因为我希望代码在需要时生成数据库。 (来自 MSDN 的示例可以在这里找到:http://msdn.microsoft.com/de-de/data/jj193542)

编辑:为了避免混淆我想做的一些事实:

  • 我有一个只有一个 Sql 用户的 MsSql 服务器设置

  • 我有要写入数据库的类。

  • 我正在尝试使用上面发布的示例来执行此操作,但是连接和/或创建数据库/数据库表失败。

最佳答案

将连接字符串添加到您的配置文件

    <configuration>
    ...

      <connectionStrings>
        <add name="DerivedClassNameFromDbContext" connectionString="Data Source=.\; Initial Catalog=DbName; Persist Security Info=True; User ID=Username; Password=pass" providerName="System.Data.SqlClient"/>
      </connectionStrings>

    ...
    </configuration>

或者在 DbContext 的派生类中使用构造函数设置连接字符串,如下所示:

public class EFDbContext : DbContext
    {
        ...

        public EFDbContext()
        {
             Database.Connection.ConnectionString =
                @"Data Source=.\; Initial Catalog=DbName; Persist Security Info=True; User ID=Username; Password=pass";
        }
    }

enter image description here

关于c# - 无法打开数据库,未创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17053621/

相关文章:

c# - 将数据库中的数据限制显示到特定行

sql-server - SQL Server 2008 SCOPE_IDENTITY() 问题

sql - 使用 TSQL SQL Server (2008 R2) 有条件地选择行

mysql - SQL Server : date incompatible with int when migrating from mysql. 如何解决?

c# - 如何调试 Entity Framework 迁移LoaderExceptions?

c# - 如何制作固定的十六进制编辑器?

c# - 连接 MS Access,而另一个应用程序使用相同的 MS Access 文件

c# - 设置匿名类型属性名

c# - TSqlUnit 值得使用吗?

c# - DbSet.Cast<TEntity>() 错误 : Cannot create a DbSet<IEntity> from a non-generic DbSet for objects of type 'Entity'