Reputation: 399
I am trying to use EntityFramework 6 with Asp.Net Core to interact with a mysql database.
I am having a really hard time trying to configure Entity Framework using code only, without all the configuration from Web.config
that can be used in "classic" .NET MVC projects.
I am stuck with a timeout while trying to connect to the database (something I can achieve in another API which relies on Web.config
, so it is definitely not a network issue).
I am currently instantiating my DataContext with a connectionString that is defined in my appsettings.json
file:
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=db.example.com;Database=dbname;Uid=user;Pwd=123123;"
}
},
Then, in my Startup.cs
:
var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
services.AddScoped((_) => new DataContext(connectionString));
Also, in DataContext.cs
, I set custom configuration using the DbConfigurationType
decorator:
public class CodeConfig : DbConfiguration
{
public CodeConfig()
{
SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlConnectionFactory());
SetProviderServices("System.Data.SqlClient",
System.Data.Entity.SqlServer.SqlProviderServices.Instance);
SetProviderServices("MySql.Data.MySqlClient", new MySql.Data.MySqlClient.MySqlProviderServices());
}
}
I am not 100% sure but I believe the problem is that I never tell EntityFramework that it is supposed to use the mysql provider, and I have absolutely no idea how I am supposed to do this.
This is the error I get and part of the stack:
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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, object providerInfo, string newPassword, SecureString newSecurePassword, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, string accessToken, bool applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource<DbConnectionInternal> retry)
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource<DbConnectionInternal> retry)
System.Data.SqlClient.SqlConnection.Open()
System.Data.Entity.Infrastructure.Interception.InternalDispatcher<TInterceptor>.Dispatch<TTarget, TInterceptionContext>(TTarget target, Action<TTarget, TInterceptionContext> operation, TInterceptionContext interceptionContext, Action<TInterceptor, TTarget, TInterceptionContext> executing, Action<TInterceptor, TTarget, TInterceptionContext> executed)
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
System.Data.Entity.SqlServer.SqlProviderServices+<>c__DisplayClass33.<UsingConnection>b__32()
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy+<>c__DisplayClass1.<Execute>b__0()
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute<TResult>(Func<TResult> operation)
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action<DbConnection> act)
System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable<int> commandTimeout, DbConnection sqlConnection, string createDatabaseScript)
System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable<int> commandTimeout, StoreItemCollection storeItemCollection)
System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
System.Data.Entity.Migrations.DbMigrator.Update(string targetMigration)
System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func<DbMigrationsConfiguration, DbContext, MigratorBase> createMigrator, ObjectContext objectContext)
System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
System.Data.Entity.CreateDatabaseIfNotExists<TContext>.InitializeDatabase(TContext context)
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
System.Data.Entity.Internal.RetryAction<TInput>.PerformAction(TInput input)
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action<InternalContext> action)
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
System.Data.Entity.Internal.Linq.InternalSet<TEntity>.Initialize()
System.Data.Entity.Internal.Linq.InternalSet<TEntity>.get_InternalContext()
System.Data.Entity.Infrastructure.DbQuery<TResult>.System.Linq.IQueryable.get_Provider()
System.Linq.Queryable.Where<TSource>(IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
Troco.ORM.Repository.UserRepository.GetUserInfoByLogin(string login) in UserRepository.cs
-- UPDATE --
After changing my configuration code to:
public class CodeConfig : DbConfiguration
{
public CodeConfig()
{
SetDefaultConnectionFactory(new MySql.Data.Entity.MySqlConnectionFactory());
SetProviderServices("MySql.Data.MySqlClient", new MySql.Data.MySqlClient.MySqlProviderServices());
}
}
It seems that now it tries to use the mysql provider. However, this error happens:
NotSupportedException: Unable to determine the provider name for provider factory of type 'MySql.Data.MySqlClient.MySqlClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
Upvotes: 1
Views: 789
Reputation: 399
As @ajawad987 point out in his comment, it is necessary to download and install Mysql Connector/NET in order to get it working without the web.config file.
https://dev.mysql.com/downloads/connector/net/
Upvotes: 2