2017-05-19 61 views
0

我有麻烦连接到代码优先方法中的SQL数据库。详情如下SQL错误实体框架代码优先方法

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

下面是上下文助手

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. 
+0

仔细检查你的连接字符串 – Adam

+0

SQL Express需要的文件是本地的。你是否尝试使用localdb或SQL的完整实例? – Eris

+0

我用连接字符串尝试了一切。你能帮我找出问题 –

回答

1

假设您的连接字符串很好, 这可能是问题所在。 我觉得你的基类的构造正在("MydbConn")数据库名称 对于基构造函数指定连接字符串我相信这是正确的方式base("name=MydbConn")

相关问题