SQL错误实体框架代码第一种方法

时间:2017-05-19 16:47:32

标签: entity-framework

我遇到了以代码优先方式连接到SQL数据库的麻烦。详情如下

<connectionStrings>
    <add name="MydbConn"
connectionString="Data Source=hostname\SQLEXPRESS;Initial Catalog=Test1;UserID=****;Password=****;Integrated Security=True"
providerName="System.Data.SqlClient"/>
  </connectionStrings>

以下是Context Helper

public class DBContext:DbContext
    {
        public DBContext():base("MydbConn")
        {
            Database.SetInitializer<DBContext>(new CreateDatabaseIfNotExists<DBContext>());
        }
        public DbSet<User> User { get; set; }
    }

用户模型

public partial class UserChatLog
    {
        [Key]
        public long UserLogId { get; set; }
        public string EnterpriseId { get; set; }
    }

最后是DBHelper文件

public void Save(User user)
        {
            DBContext context = new DBContext();
            context.User.Add(User);
            context.SaveChangesAsync();
        }

我收到以下异常

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: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.

1 个答案:

答案 0 :(得分:1)

假设您的连接字符串正常, 这可能是问题所在。 我认为你的基础构造函数将("MydbConn")作为数据库名称 为了在基础构造函数中指定连接字符串,我相信这是正确的方法base("name=MydbConn")

相关问题