2012-06-18 22 views
10

我试图使用代码优先与我的本地实例Sql Server 2008 R2。我创建了一个用户'dev',并可以使用Sql Managment Studio登录并创建数据库。问题是我试图在EntityFramework中使用DbContext创建数据库时收到错误消息。这是错误信息:实体框架代码第一个错误“错误定位服务器/实例指定”

"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. SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified"

错误消息我检查了我的Sql Server,它确实允许远程连接。

我抽象我的系统用下面的代码,并得到了同样的错误:

namespace CodeFirstConsole 
{ 
    public class Program 
    { 
     static void Main(string[] args) 
     { 
      var db = new MyContext(); 
      try { Console.WriteLine(db.Parents.Count()); } 
      catch (Exception) { throw; } 
      Console.Read(); 
     } 
    } 

    internal class MyContext : DbContext 
    { 
     public DbSet<ParentObject> Parents { get; set; } 
     public DbSet<ChildObject> Children { get; set; } 

     public MyContext() 
     { 
      this.Database.Connection.ConnectionString = 
       "Data Source=.;Database=ConsoleTest;Initial Catalog=ConsoleTest;User ID=dev;Password=dev;"; 
     } 
    } 

    internal class ParentObject 
    { 
     public int Id { get; set; } 
     public string PropertyOne { get; set; } 
    } 

    internal class ChildObject 
    { 
     public int Id { get; set; } 
     public bool PropertyOne { get; set; } 
     public string PropertyTwo { get; set; } 

     public virtual ParentObject Parent { get; set; } 
    } 

    internal class MyInitializer : DropCreateDatabaseAlways<MyContext> 
    { 

     protected override void Seed(MyContext context) 
     { 
      context.Parents.Add(new ParentObject() { PropertyOne = "hi" }); 
      base.Seed(context); 
     } 
    } 
} 
+0

你是否明确地指定了数据源,我知道如果你把它留为空白,它认为它是同一台机器,但试着把它放进去,看看你是否得到相同的结果。 –

+0

是的,当我设置连接字符串时,我在我的示例中明确指定了它。 –

+1

只需检查您写的上面的代码是否也位于您连接的SQL Server计算机上?只是检查。 –

回答

21

我有这样的驱使我坚果一天左右了同样的错误。我的情况是我有一个预先存在的启动项目的大型解决方案,我正在将EF添加到持久性项目。

所以第一步是添加EF依赖项。这使用正确的EF内容在我的持久性项目中创建了一个app.config。然后我去了Enable-Migrations,并在这篇文章中得到了同样的错误。在这一点上,我没有考虑将EF app.config设置复制到启动项目的app.config,因为我认为在最终运行该应用程序之前我必须先尝试使用它。

当我将解决方案启动项目更改为持久性项目时,问题已解决,因此我可以使用EF来查找正确的app.config。或者我可以将EntityFramwework相关部分复制到启动项目的app.config。

+2

非常感谢。我对此感到头痛。 –

+0

这个答案可能只是保存了我的小时!谢谢 –

+2

启动项目...!你应该拥抱一下! – Lernkurve

0

不得不将EntityFramework依赖项也添加到启动项目中。

Install-Package EntityFramework 

而且还必须定义connectionStrings到我的主项目App.config/Web.config。

<connectionStrings> 
    <add name="Database" providerName="System.Data.SqlClient" connectionString="foo.bar" /> 
</connectionStrings> 
1

有同样的错误消息,在本地发展,但昨天工作正常。 发现解决方案中的错误项目设置为启动项目。

因此,如果您在包管理器控制台中的update-database命令之后也收到此消息,请务必检查是否设置了正确的启动项目。

例如Web项目,而不是帮助程序项目之一。 视觉工作室似乎有其自己有时将其他项目设置为启动的习惯...

0

我有同样的问题,花了一整天的时间。终于找到@ Christian的答案,现在我找到了一个更好的方法!

ConnectionString放在启动项目中。因此,每次更改实体时都不需要切换。

相关问题