为什么EF迁移的连接字符串无法工作?

3
我已经创建了一个数据库,用于与NuGet Gallery实现配合使用。我可以在SQL Manager 2012中看到该数据库,并且通过测试程序和我的连接字符串访问它。但是,当我尝试在软件包管理器控制台中运行Update-Database命令,让EF设置数据库时,我一直收到错误消息:“服务器未找到或无法访问”。以下是更多详细信息:
PM> Update-Database -Verbose

Using StartUp project 'NuGetGallery.Operations'. 
Using NuGet project 'NuGetGallery'. 
Specify the '-Verbose' flag to view the SQL statements being applied to the target database. 

System.Data.ProviderIncompatibleException: 
An error occurred while getting provider information from the database. 
This can be caused by Entity Framework using an incorrect connection string.
Check the inner exceptions for details and ensure that the connection string is correct. ---> 

System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> 

System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26

- Error Locating Server/Instance Specified)    at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)    at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)

这是NuGet Gallery MVC网站中我的连接字符串:

    <add name="Gallery.SqlServer" connectionString="Server=(localdb)\v11.0;Database=NuGetGallery11;User ID=testuser;Password=notmyrealpassword;Connect Timeout=60" providerName="System.Data.SqlClient"/>

下面是我的测试程序,两个应用程序中的连接字符串是相同的。

            var sqlConnection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Gallery.SqlServer"].ConnectionString);
        sqlConnection2.Open();
        using (sqlConnection2) {
            var sqlCmd = new SqlCommand("select * from Foo", sqlConnection2);

            var foo = sqlCmd.ExecuteReader();
            while (foo.Read()) {
                int id = foo.GetInt32(0);
                var name = foo.GetString(1);
                var email = foo.GetString(2);

                Console.WriteLine("ID:{0}, Name:{1}, Email:{2}", id, name, email);

            }
        }
        Console.Read();

非常感谢您的帮助,如果有需要,请随时联系我们。谢谢!


你需要在谷歌上搜索如何格式化连接字符串,以便通过EF连接到数据库。这里有一个链接,你可以查看其中的工作示例C#连接字符串 - MethodMan
哪个类应该从DbContext派生? - Aydin
2个回答

4

我的问题在这里的帖子中得到了解决。你需要在管理控制台中设置默认项目并设置解决方案的启动项目,以便更新命令能够找到连接字符串,还要遵循Aydin所说的,但在我的情况下,这部分已经为我设置好了。


并将启动项目设置为解决方案,以便更新命令可以找到连接字符串。这解决了我的问题。谢谢。谢谢。谢谢! - ChettDM

1
您的问题是EntityFramework不知道您的连接字符串名为Gallery.SqlServer...。以下是如何从头开始设置实体框架的方法...
  1. Open VS with Administrative rights (just being cautious)
  2. Create a new Console application
  3. Open the package manager console
    • Type in: `PM> Install-Package EntityFramework
  4. Open the App.Config file

    • Add the following

      <connectionStrings>
        <add name="Gallery.SqlServer" connectionString="Server=(localdb)\v11.0;Database=GalleryExample;" providerName="System.Data.SqlClient"/>
      </connectionStrings>
      
  5. Create a new class called Foo

    public class Foo
    {
        public Foo()
        {
            this.Id = Guid.NewGuid()
                          .ToString();
        }
    
        public string Id { get; set; }
    }
    
  6. Create a new class called EfContext

    public class EfContext : DbContext
    {
        public EfContext()
            : base("Gallery.SqlServer")
        {
    
        }
        public DbSet<Foo> Foos { get; set; }
    }
    
  7. Open up the package manager console again

    • PM> Enable-Migrations
    • PM> Add-Migration InitialMigration
    • PM> Update-Database
  8. Enjoy your new db....


Aydin,感谢您的帮助。这对于创建一个简单的示例很有用,但我仍然不明白为什么我的代码不起作用。明确一下,这是NuGet Gallery的源代码,来自其github存储库,应该完全可用。它已经有一个构造函数,以迁移的连接名称作为参数:public EntitiesContext() : base("Gallery.SqlServer") // 使用web.config中的连接字符串(如果找到) { } - Dan Csharpster
1
你的凭据可能是罪魁祸首……据我所知,LocalDB使用Windows身份验证,如果我的示例可以工作而其他示例不能,则必须是你的连接字符串有问题。而且,我连接字符串和你的唯一区别就是你的尝试传递用户名和密码。 - Aydin
我找到答案了!除了在包管理器控制台中将默认项目设置为NuGetGallery之外,您还必须将NuGetGallery设置为解决方案的启动项目,才能从正确的web.config文件中读取。这似乎有些烦人和冗余,因为您不得不两次指定该项目以查找web.config和连接字符串,但我想这就是微软的风格。 - Dan Csharpster
哈哈哈哈,我很惊讶自己竟然忽略了这一点,因为通常我会将实体框架和领域模型放在一个单独的库中,然后在应用迁移时明确地针对它们进行目标设置。 - Aydin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接