EF6 透過 NuGet 獨立發布、開源開發,已超越早期「僅適合原型」的刻板印象,成為生產級 ORM 首選。本文依功能層次分類解析專家級特性。
// 查詢 await context.Customers.FirstOrDefaultAsync(c => c.Id == id); await context.Customers.ToListAsync(); // 異動 await context.SaveChangesAsync(); // Find 非同步 var customer = await context.Customers.FindAsync(id);
對應 System.Data.Entity.QueryableExtensions 與 DbContext 擴充方法。
// 所有 string 欄位預設長度 50
modelBuilder.Properties<string>()
.Configure(p => p.HasMaxLength(50));
// 強制自訂約定優先於內建約定
modelBuilder.Conventions.AddBefore<CustomConvention>(typeof(PrimaryKeyNameConvention));
public class MyDbConfiguration : DbConfiguration {
public MyDbConfiguration() {
SetExecutionStrategy(SqlProviderServices.ProviderInvariantName,
() => new SqlAzureExecutionStrategy());
}
}
SqlAzureExecutionStrategy 針對 Azure SQL 暫時性錯誤自動重試 (預設 5 次、指數退避)IDbExecutionStrategy 實作專屬重試邏輯using (var tx = context.Database.BeginTransaction()) {
try {
context.SaveChanges();
context.Database.ExecuteSqlCommand("UPDATE ...");
tx.Commit();
} catch { tx.Rollback(); }
}

圖 1 預設:SaveChanges 與 ExecuteSqlCommand 各自交易

圖 2 BeginTransaction 共用單一交易
context.Casinos.AddRange(new[] { casino1, casino2 }); // 單次 DetectChanges
DetectChanges 成本SaveChanges 仍逐筆送出 SQL,非批次執行EF6 內部使用 ObjectReferenceEqualityComparer,不再受領域模型覆寫 Equals 干擾,解決 DDD 值物件與變更追蹤衝突。
public class Casino {
public Address PhysicalAddress { get; set; }
public class Address : ValueObject<Address> { ... } // 巢狀類別
}

圖 3 EF6 正確識別巢狀 Address 型別,EF5 則忽略
public class MyInterceptor : IDbCommandInterceptor {
public void ReaderExecuting(DbCommand cmd, ...) {
Log(cmd.CommandText); // 記錄或修改 SQL
}
// 其他介面方法...
}
註冊:DbInterception.Add(new MyInterceptor());
public class MyPluralization : IPluralizationService {
public string Pluralize(string word) { ... }
public string Singularize(string word) { ... }
}
// 註冊
DbConfiguration.SetPluralizationService(new MyPluralization());
Update-Database -Script 供 DBA 審核__MigrationHistory 表結構可自訂適配非 SQL ServermodelBuilder.Configurations.AddFromAssembly 批次載入設定類別遷移提示:EF5→EF6 命名空間變更 (
System.Data.Entity→System.Data.Entity.Core),官方提供 遷移指南。
作者:玄魂 (改編自 MSDN Magazine Data Points 專欄)
出處:https://www.cnblogs.com/xuanhun/