使用MySQL 5,简单的成员资格提供程序,ASP.NET MVC4实体框架5 [英] Using MySQL 5 , Simple Membership Provider, ASP.NET MVC4 with Entity Framework 5

查看:147
本文介绍了使用MySQL 5,简单的成员资格提供程序,ASP.NET MVC4实体框架5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想:
使用简单的成员资格提供基础的身份验证使用ASP.NET MVC的MySQL 4 默认Web应用程序配置为使用MySQL使用给定教程:
<一href=\"http://www.nsilverbullet.net/2012/11/07/6-steps-to-get-entity-framework-5-working-with-mysql-5-5/\" rel=\"nofollow\">http://www.nsilverbullet.net/2012/11/07/6-steps-to-get-entity-framework-5-working-with-mysql-5-5/

I am trying to: use Simple Membership provider based authentication with MySQL using ASP.NET MVC 4 default web application configured to use MySQL using the tutorial given at: http://www.nsilverbullet.net/2012/11/07/6-steps-to-get-entity-framework-5-working-with-mysql-5-5/

和在这里 ASP.NET MVC 4 EF5与MySQL

我使用的的MySQL Connector 6.6.4 EF 5.0 的Visual Studio 2012 并用 ASP.NET MVC工作4互联网应用模板。

I am using MySQL Connector 6.6.4 with EF 5.0 and Visual Studio 2012 and working with an ASP.NET MVC 4 Internet application template.

Server Error in '/' Application.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[UserId] FROM [UserProfile] WHERE (UPPER([UserName]) = 'Z')' at line 1
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: MySql.Data.MySqlClient.MySqlException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[UserId] FROM [UserProfile] WHERE (UPPER([UserName]) = 'Z')' at line 1

Source Error:


Line 55:                     }
Line 56: 
Line 57:                     WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: false);
Line 58:                 }
Line 59:                 catch (Exception ex)


Source File: e:\Projects\TestApp\TestApp\TestApp\Filters\InitializeSimpleMembershipAttribute.cs    Line: 57

我的code是:

InitializeSimpleMembershipAttribute.cs

private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                //Database.SetInitializer<UsersContext>(null);
                //Database.SetInitializer(new DropCreateMySqlDatabaseIfModelChanges<UsersContext>());
                //Database.SetInitializer(new CreateMySqlDatabaseIfNotExists<UsersContext>());
                Database.SetInitializer(new DropCreateMySqlDatabaseIfModelChanges<UsersContext>());
                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            //((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                            //context.Database.CreateIfNotExists();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: false);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }

        }

AccountModel.cs(相关$ C $仅C)

public class UsersContext : DbContext
    {
        static UsersContext()
        {
            //Database.SetInitializer(new DropCreateMySqlDatabaseIfModelChanges<UsersContext>());
        }
        public UsersContext()
            : base("DefaultConnection")
        {
            //Database.SetInitializer(new DropCreateMySqlDatabaseIfModelChanges<UsersContext>());
        }

        public DbSet<UserProfile> UserProfiles { get; set; }
    }
    public class DropCreateMySqlDatabaseAlways<TContext>
      : MySqlDatabaseInitializer<TContext> where TContext : DbContext
    {
        public override void InitializeDatabase(TContext context)
        {
            context.Database.Delete();
            CreateMySqlDatabase(context);
        }
    }

    public class DropCreateMySqlDatabaseIfModelChanges<TContext>
     : MySqlDatabaseInitializer<TContext> where TContext : DbContext
    {
        public override void InitializeDatabase(TContext context)
        {
            bool needsNewDb = false;
            if (context.Database.Exists())
            {
                if (!context.Database.CompatibleWithModel(false))
                {
                    context.Database.Delete();
                    needsNewDb = true;
                }
            }
            else
            {
                needsNewDb = true;
            }
            if (needsNewDb) CreateMySqlDatabase(context);
        }
    }

    public class CreateMySqlDatabaseIfNotExists<TContext>
   : MySqlDatabaseInitializer<TContext> where TContext : DbContext
    {
        public override void InitializeDatabase(TContext context)
        {
            if (context.Database.Exists())
            {
                if (!context.Database.CompatibleWithModel(false))
                {
                    throw new InvalidOperationException(
                        "The model has changed!");
                }
            }
            else
            {
                CreateMySqlDatabase(context);
            }
        }
    }

    public abstract class MySqlDatabaseInitializer<TContext>
     : IDatabaseInitializer<TContext>
         where TContext : DbContext
    {
        public abstract void InitializeDatabase(TContext context);

        protected void CreateMySqlDatabase(TContext context)
        {
            try
            {
                // Create as much of the database as we can
                context.Database.Create();

                // No exception? Don't need a workaround
                return;
            }
            catch (MySqlException ex)
            {
                // Ignore the parse exception
                if (ex.Number != 1064)
                {
                    throw;
                }
            }

            // Manually create the metadata table
            using (var connection = ((MySqlConnection)context
                .Database.Connection).Clone())
            using (var command = connection.CreateCommand())
            {
                command.CommandText =
    @"
CREATE TABLE __MigrationHistory (
    MigrationId mediumtext NOT NULL,
    Model mediumblob NOT NULL,
    ProductVersion mediumtext NOT NULL);

ALTER TABLE __MigrationHistory
ADD PRIMARY KEY (MigrationId(255));

INSERT INTO __MigrationHistory (
    MigrationId,
    Model,
    ProductVersion)
VALUES (
    'InitialCreate',
    @Model,
    @ProductVersion);
";
                command.Parameters.AddWithValue(
                    "@Model",
                    GetModel(context));
                command.Parameters.AddWithValue(
                    "@ProductVersion",
                    GetProductVersion());

                connection.Open();
                command.ExecuteNonQuery();
            }
        }

        private byte[] GetModel(TContext context)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var gzipStream = new GZipStream(
                    memoryStream,
                    CompressionMode.Compress))
                using (var xmlWriter = XmlWriter.Create(
                    gzipStream,
                    new XmlWriterSettings { Indent = true }))
                {
                    EdmxWriter.WriteEdmx(context, xmlWriter);
                }

                return memoryStream.ToArray();
            }
        }

        private string GetProductVersion()
        {
            return typeof(DbContext).Assembly
                .GetCustomAttributes(false)
                .OfType<AssemblyInformationalVersionAttribute>()
                .Single()
                .InformationalVersion;
        }
    }

    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }
    }

    public class RegisterExternalLoginModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        public string ExternalLoginData { get; set; }
    }

    public class LocalPasswordModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        public string OldPassword { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm new password")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

请帮我找出什么我做错了。谢谢

Kindly help me finding out what i am doing wrong. Thanks

推荐答案

我这里提供一个类似的问题的答案:
<一href=\"http://stackoverflow.com/questions/12620922/using-simple-membership-provider-with-mysql/15800614#15800614\">Using简单的成员资格提供与MySQL
它是基于一种本文从法比奥科斯塔我发现这里:<一href=\"http://fabiocanada.ca/2012/11/24/use-simplemembership-and-oauth-with-any-database-and-datatype/\" rel=\"nofollow\">http://fabiocanada.ca/2012/11/24/use-simplemembership-and-oauth-with-any-database-and-datatype/.你基本上得到源$ C ​​$ C,将其更新到您的需要(让我们把它写的MySQL查询,而不是SQL),并使用它。

I provided an answer on a similar question here: Using Simple Membership Provider with mysql It's based on a article from Fabio Costa I found here: http://fabiocanada.ca/2012/11/24/use-simplemembership-and-oauth-with-any-database-and-datatype/. You basically get the source code, update it to your needs (let it write mysql queries instead of sql) and use that.

这篇关于使用MySQL 5,简单的成员资格提供程序,ASP.NET MVC4实体框架5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆