asp.net核心+ef6+mysql

42fyovps  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(645)

我正在尝试使用EntityFramework6和asp.net核心来与mysql数据库交互。
我真的很难尝试只使用代码来配置实体框架,而不需要所有的配置 Web.config 可以在“classic”.NETMVC项目中使用。
我在尝试连接到数据库时遇到了超时(我可以在另一个依赖于的api中实现这一点) Web.config ,所以绝对不是网络问题)。
我当前正在用我的数据库中定义的connectionstring示例化我的datacontext appsettings.json 文件:

"Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=db.example.com;Database=dbname;Uid=user;Pwd=123123;"
    }
  },

然后,在我的 Startup.cs :

var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
        services.AddScoped((_) => new DataContext(connectionString));

另外,在 DataContext.cs ,我使用 DbConfigurationType 装饰师:

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());

    }
}

我不是100%肯定,但我相信问题是我从来没有告诉entityframework它应该使用mysql提供程序,我完全不知道我应该如何做到这一点。
这是我得到的错误和堆栈的一部分:
sqlexception:建立到sql server的连接时发生与网络相关或特定于示例的错误。找不到或无法访问服务器。验证示例名称是否正确,以及sql server是否配置为允许远程连接(提供程序:命名管道提供程序,错误:40-无法打开到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

--更新--
将配置代码更改为:

public class CodeConfig : DbConfiguration
    {
        public CodeConfig()
        {
            SetDefaultConnectionFactory(new MySql.Data.Entity.MySqlConnectionFactory());
            SetProviderServices("MySql.Data.MySqlClient", new MySql.Data.MySqlClient.MySqlProviderServices());

        }
    }

似乎现在它尝试使用mysql提供程序。但是,会发生以下错误:
notsupportedexception:无法确定“mysql.data.mysqlclient.mysqlclientfactory”类型的提供程序工厂的提供程序名称。确保已在应用程序配置中安装或注册ado.net提供程序。

sycxhyv7

sycxhyv71#

正如@ajawad987在他的评论中指出的那样,有必要下载并安装mysql connector/net,以使其在没有web.config文件的情况下工作。
https://dev.mysql.com/downloads/connector/net/

相关问题