EF6连接MySQL若干问题汇总
中文乱码问题
连接字符串已经设置charset=utf8,但依旧出现乱码,解决方法:配置字符串字段约定支持Unicode
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Properties<string>().Configure(x => x.IsUnicode(true)); }
数据库级联删除问题
抛出的异常类似于“Introducing FOREIGN KEY constraint '' on table '' may cause cycles or multiple cascade paths.”,解决方法:删除默认的一对多级联删除约定
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); }
定义唯一约束问题
EF6中支持定义唯一约束,方法:对需要被定义为唯一约束的属性添加索引特性。
[System.ComponentModel.DataAnnotations.Schema.Index(IsUnique = true)] public string Code { get; set; }
__Migrationhistory表中主键超出最大长度问题
自定义数据库配置类,该类继承于DbConfiguration,属于全局配置类,代码如下:
public class MySqlConfiguration : DbConfiguration { public MySqlConfiguration() { SetHistoryContext("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema)); } } 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(); } }