您的位置:首页 > 数据库 > MySQL

entityframework Identity codefirst 使用MySql作为数据存储的笔记

2016-09-12 10:34 741 查看
1.下载MySql连接for .net

下载地址:http://dev.mysql.com/downloads/connector/net/

2.新建asp.net MVC项目

3.添加引用 MySql.Data和MySqlData.EntityEF6

修改项目根目录下web.config

在<entityFramework>块填加如下:

<provider invariantName="MySql.Data.MySqlClient"
type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>


添加

<system.data>
<DbProviderFactories>
<add name="MySql Data Provider"
invariant="MySql.Data.MySqlClient"
description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data,Version=6.9.9.0 , Culture=neutral, PublicKeyToken=c5687fc88969c44d"  />
</DbProviderFactories>
</system.data>


并注释掉,因为本地已经安装了mysql connector/net,如果不注释掉,会出现 invariant是唯一的出错。发布时,如果服务器找不到对象(没有安装mysqlconnector/net)则需要这一段。

3.添加连接字符窜:

在〈connectionStrings〉块,添加

<add name="MySqlConnection" connectionString="Server=192.168.0.100;Port=3306;User Id=root;Password=123456;Database=MyDatabase;CharSet=utf8"
providerName="MySql.Data.MySqlClient" />


注:以上Server,Port,User Id,Database,根据自身项目需要自行修改。

这一切修改好后,基本可以使用MySql作为数据库存储

但是在实际应用中,使用asp.net Identity会出更数据库、表不存在的错误。

查看一下asp的官方教程。

原因是Entity Framework Code First使用MigrationHistory表来跟踪模型变化,并使数据架构模型设计架构一致。但是由于主键太长,所以默认情况下不能在MySql下工作。

(Entity Framework Code First uses a MigrationHistory table
to keep track of model changes and to ensure the consistency between the database schema and conceptual schema. However, this table does not work for MySQL by default because the primary key is too large.)

所以必须要重载HistoryContext。

1.添加新类 MySqlHistoryContext 

using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Migrations.History;

namespace IdentityMySQLDemo
{
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();
}
}
}


2.配置HistoryContext.

添加MySqlConfiguration类

using System.Data.Entity;

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


3.为ApplicationDbContext创建 自定义的的初始化对象


4000
加类MySqlInitializer

using IdentityMySQLDemo.Models;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;

namespace IdentityMySQLDemo
{
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();
}
}
}
}
}

4.修改Models目录下的IdentityModels.cs

using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;

namespace IdentityMySQLDemo.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser
// class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
}

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

public ApplicationDbContext()
: base("MySqlConnection")
{
}
}
}

然后就可以CTRL+F5,运行,
试一下右上角的“注册”

自动创建各数据表

至于,修改数据表名,网上已经很多了。随便搜一下就有。

写下以上笔记,备以后参考用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐