# EF6 經典模式 Install-Package EntityFramework -Version 6.4.4 Install-Package MySql.Data.EntityFramework -Version 8.0.33 # EF Core 現代模式 Install-Package Microsoft.EntityFrameworkCore -Version 8.0.0 Install-Package MySql.EntityFrameworkCore -Version 8.0.33
public class User
{
public int Id { get; set; }
[StringLength(30)] // 必須指定長度!對應 VARCHAR(30)
public string UserName { get; set; }
[MaxLength(30)] // 或用 MaxLength
public string PassWord { get; set; }
[Column(TypeName = "VARCHAR(100)")] // 显式指定類型
public string Email { get; set; }
}
原因:EF 默認 string → LONGTEXT,MySQL 索引限制 767 字節 (utf8mb4 下 191 字符),超長報錯。
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyContext : DbContext
{
public MyContext() : base("name=MyContext") { }
public DbSet Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// 可在此處統一配置字符串默認長度
modelBuilder.Properties()
.Configure(p => p.HasMaxLength(255));
}
}
public class MyContext : DbContext
{
public DbSet Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("Server=localhost;Port=3306;Database=MySQL_EF;Uid=root;Pwd=root;Charset=utf8mb4;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(e =>
{
e.Property(p => p.UserName).HasMaxLength(30).IsRequired();
e.Property(p => p.Email).HasColumnType("VARCHAR(100)");
});
}
}
{
"ConnectionStrings": {
"Default": "Server=localhost;Port=3306;Database=MySQL_EF;Uid=root;Pwd=root;Charset=utf8mb4;SslMode=Preferred;"
}
}
| 錯誤現象 | 原因 | 解決 |
|---|---|---|
| Specified key was too long; max key length is 767 bytes | string 無長度限制 → LONGTEXT → 索引超限 | 實體屬性加 [StringLength(n)] / HasMaxLength(n) |
| Model compatibility cannot be checked because the database does not contain model metadata | 數據庫已存在但無 __MigrationHistory / 模型不匹配 | 刪除庫重建 / Enable-Migrations + Add-Migration Initial |
| 序列不包含任何匹配元素 | 外鍵/導航屬性配置錯誤 (如 WithMany/WithOptional 混淆) | 檢查 Fluent API:HasMany/WithOne, HasOne/WithMany 配對正確 |
| Unknown column 'Extent1.Id' in 'field list' | 實體主鍵未標識 [Key] 或命名不符約定 | 加 [Key] / modelBuilder.Entity |
| SSL connection error / Authentication plugin error | MySQL 8.0 默認 caching_sha2_password | 連接串加 SslMode=Preferred; 或創建用戶指定 mysql_native_password |
| Charset=utf8mb4 不生效 | 庫/表創建時字符集不一致 | 創建庫指定 CHARSET=utf8mb4; EF 遷移腳本中指定 |
# 1. 啟用遷移 Enable-Migrations -ContextTypeName MyContext # 2. 添加初始遷移 Add-Migration InitialCreate # 3. 更新數據庫 Update-Database -Verbose
Pooling=true;MinPoolSize=5;MaxPoolSize=100;EF + MySQL 核心衝突點在於 **類型映射預設值差異**。掌握「字符串強長度、字符集統一、遷移管理」三板斧,即可平穩落地。