.NET 6下EF Core7替代DbModelBuilder约定及ExecuteSqlCommand方法咨询
EF Core 7.0.2 替代传统.NET EF功能方案
1. 替代DbModelBuilder.Conventions的约定管理
EF Core 7中没有DbModelBuilder.Conventions集合,改用ConfigureConventions方法在OnModelCreating里管理约定,具体操作如下:
- 移除默认约定:针对全局默认约定(比如复数表名规则),可在
ConfigureConventions中调用Remove方法移除对应约定类,示例:protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ConfigureConventions(config => { // 移除复数表名约定 config.Remove(typeof(PluralizingTableNameConvention)); }); // 其他模型配置逻辑 } - 添加自定义约定:自定义实现
IConvention接口的约定类,再通过ConfigureConventions的Add方法注册,示例:public class MyCustomConvention : IModelFinalizingConvention { public void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext<IConventionModelBuilder> context) { // 自定义约定逻辑,比如统一设置实体表名前缀 foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { entityType.SetTableName($"tbl_{entityType.ClrType.Name}"); } } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ConfigureConventions(config => { config.Add<MyCustomConvention>(); }); } - 若只是针对单个实体修改规则(比如指定表名),直接用数据注解
[Table("MyTable")]或Fluent APImodelBuilder.Entity<MyEntity>().ToTable("MyTable")更直接,无需全局修改约定。
2. 替代ExecuteSqlCommand/ExecuteSqlCommandAsync方法
EF Core 7已废弃上述方法,改用以下两组参数化SQL执行方法:
- ExecuteSqlRaw/ExecuteSqlRawAsync:用于执行带参数的原始SQL,支持占位符或命名参数,示例:
// 同步执行 int affectedRows = Database.ExecuteSqlRaw("UPDATE Products SET Price = Price * 1.1 WHERE CategoryId = @p0", categoryId); // 异步执行 int affectedRowsAsync = await Database.ExecuteSqlRawAsync( "UPDATE Products SET Price = Price * 1.1 WHERE CategoryId = @categoryId", new SqlParameter("@categoryId", categoryId) ); - ExecuteSqlInterpolated/ExecuteSqlInterpolatedAsync:支持插值SQL写法,EF Core会自动将插值内容转为参数化查询,避免SQL注入,示例:
// 同步执行 int affectedRows = Database.ExecuteSqlInterpolated($"UPDATE Products SET Price = Price * 1.1 WHERE CategoryId = {categoryId}"); // 异步执行 int affectedRowsAsync = await Database.ExecuteSqlInterpolatedAsync($"UPDATE Products SET Price = Price * 1.1 WHERE CategoryId = {categoryId}");
注意:动态拼接SQL时必须用参数化方式,禁止直接拼接字符串防止注入风险。
内容的提问来源于stack exchange,提问作者Lucky
相关产品推荐
相关产品推荐

