c# - EF 代码优先 : Cannot connect to SQL Server

标签 c# .net sql-server entity-framework ado.net

我正在尝试使用代码优先方法创建数据库。当我运行以下代码时,出现以下异常。我们如何克服这个问题?

注意事项:

  • 我的系统上有 SQL Server 2008 R2。
  • 我没有使用任何配置文件。我假设它将使用约定创建数据库
  • 还没有打开的连接;我刚刚重新启动系统并进行了测试。还是一样的问题。
  • EntityFramework.dll 的运行时版本是 v4.0.3xxx

异常:

The provider did not return a ProviderManifestToken string

留言:

This operation requires a connection to the 'master' database. Unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. Supply an unopened connection.

内部异常:

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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

代码:

using System.Data.Entity;
namespace LijosEF
{
  public class Dinner
  {
      public int DinnerID { get; set; }
      public int Title { get; set; }
  }

  public class RSVP
  {
    public int RSVPID { get; set; }
    public int DinnerID { get; set; }

    public virtual Dinner Dinner { get; set; }
  }

  //System.Data.Entity.DbContext is from EntityFramework.dll
  public class NerdDinners : System.Data.Entity.DbContext
  {
    public DbSet<Dinner> Dinners { get; set; }
    public DbSet<RSVP> RSVPs { get; set; }
  }
}

namespace LijosEF
{
class Program
{
    static void Main(string[] args)
    {
        using (var db = new NerdDinners())
        {
            var product = new Dinner { DinnerID = 1, Title = 101 };
            db.Dinners.Add(product);
            int recordsAffected = db.SaveChanges();
        }

    }
}
}

最佳答案

没有任何连接信息。 EF 将尝试在 SQL Express 而不是 SQL Server 中创建数据库。如果您希望在 SQL Server 中创建它,您将需要提供一个连接字符串。

关于c# - EF 代码优先 : Cannot connect to SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11580431/

相关文章:

c# - 当我的代码迁移落后于数据库迁移时, Entity Framework 如何找到 Down() 方法?

c# - 将数据从 Html.Action 传递到局部 View

sql - 程序时间执行计数器

c# - 应用程序文件夹的权限

c# - 加载 MITab dll 在 c# 中给出 System.BadImageFormatException

c# - 如何正确管理 TPL 数据流中的完成

c# - 关于多线程的问题

c# - 如何将参数传递给 C# 中的直通查询?

c# - 如何使用 C# ADO.Net 从 SQL Server 插入命令获取多行输出?

c# - 将以毫秒为单位的日期时间转换为 double 或 int?