简体   繁体   中英

Error when connecting MySQL from Entity Framework

I am following this tutorial to create a mvc application connecting to mysql and getting this error.

An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code, Additional information: Specified key was too long; max key length is 1000 bytes

I followed everything from the tutorial apart from my mysql database is on godaddy rather than on azure. New database and new MVC Application in VS2013 .Net 4.5.1. EF 6.1.3 and MySQL.Data.Entity version is 6.9.8.

The error is on this line.

context.Database.Create();

I found some people got same problem but their solution isn't using SetInitializer like in this tutorial. I hope some one can point out what I'm doing wrong.

public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
    {

        public void InitializeDatabase(ApplicationDbContext context)
        {
            if (!context.Database.Exists())
            {
                // if database did not exist before - create it
                context.Database.Create();
            }
            else
            {
                // query to check if MigrationHistory table is present in the database 
                var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
                string.Format(
                  "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'", "users"));

                // if MigrationHistory table is not there (which is the case first time we run) - create it
                if (migrationHistoryTableExists.FirstOrDefault() == 0)
                {
                    context.Database.Delete();
                    context.Database.Create();
                }
            }
        }
    }

 public class MySqlHistoryContext : HistoryContext
{
    public MySqlHistoryContext(
              DbConnection existingConnection,
              string defaultSchema)
        : base(existingConnection, defaultSchema)
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
        modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
    }
}

public class MySqlConfiguration : DbConfiguration
{
    public MySqlConfiguration()
    {
        SetHistoryContext(
        "MySql.Data.MySqlClient", (conn, schema) => new      MySqlHistoryContext(conn, schema));
    }
}

public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        static ApplicationDbContext()
        {
            Database.SetInitializer(new MySqlInitializer());
        }

    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

This can be done in three ways:

Adding the DbConfigurationTypeAttribute on the context class:

[DbConfigurationType(typeof(MySqlEFConfiguration))]

Calling DbConfiguration.SetConfiguration(new MySqlEFConfiguration()) at the application startup Set the DbConfiguration type in the configuration file:

<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">

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