0

I am having troubles connecting to SQL database in code first approach. Details are as below

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

Below is the Context Helper

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

The User Model

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

And Finally DBHelper file

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

I am getting the below exception

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.
4
  • double check your connection string Commented May 19, 2017 at 16:49
  • SQL Express requires the file to be local. Are you trying to use localdb, or a full instance of SQL? Commented May 19, 2017 at 16:51
  • I tried everything with the connection string. Could you please help me identify the issue Commented May 19, 2017 at 16:51
  • I am trying to create Database based on my context on my local SQL 2014 server Commented May 19, 2017 at 16:52

1 Answer 1

1

Assuming that your connection string is fine, this might be the problem. I think your base constructor is taking ("MydbConn") as database name For specifying connection string in the base constructor i believe this is the right way base("name=MydbConn")

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.