简体   繁体   中英

Entity Framework MySQL DbContext cannot connect

I created a models using code-first and without storing password in App.config, I passing it in constructor of DbContext instead:

public TasksWithoutPasswordContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
    this.Database.Connection.ConnectionString = nameOrConnectionString;
}

But I got a runtime error while trying to get DbSet of my DbContext:

using (TasksWithoutPasswordContext contextWithoutPassword = new TasksWithoutPasswordContext(connectionString))
{
    foreach (var user in contextWithoutPassword.users)
    {
        MessageBox.Show(user.user);
    }
}

Additional information: 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).

I tried to mark my class as next:

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class TasksWithoutPasswordContext : DbContext

and it didn't helped.

As you already found the solution yourself, I add the answer:

When you're inheriting from DbContext and call the base constructor, you could use the default-base-constructor (the parameterless one) and set the connectionstring in constructor:

public TasksWithoutPasswordContext(string nameOrConnectionString) : base() 
{
    this.Database.Connection.ConnectionString = nameOrConnectionString;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM