我试图使用代码优先与我的本地实例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);
}
}
}
你是否明确地指定了数据源,我知道如果你把它留为空白,它认为它是同一台机器,但试着把它放进去,看看你是否得到相同的结果。 –
是的,当我设置连接字符串时,我在我的示例中明确指定了它。 –
只需检查您写的上面的代码是否也位于您连接的SQL Server计算机上?只是检查。 –