英文:
How to trim all char fields (C# string) before writing to database for all tables and all add or updates in EF Core?
问题
我希望 EF Core 在将数据写入数据库之前,自动将所有表(实体)和所有添加或更新操作的所有字符字段(C# 字符串)修剪。
英文:
I want EF Core to trim all char fields (C# strings) automatically before writing to the database for all tables (entities) and all add or update operations.
答案1
得分: 3
You can achieve this by overriding the SaveChanges method of your DbContext class. In the overridden method, you can iterate through all the entities in the ChangeTracker and trim all the string properties before saving the changes to the database.
** AppDbContext.cs **
public partial class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public virtual DbSet<Company> Companies { get; set; }
... // other DbSets
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
** AppDbContextPartial.cs **
public partial class AppDbContext
{
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
TrimStringProperties();
return await base.SaveChangesAsync(cancellationToken);
}
private void TrimStringProperties()
{
var entries = ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
foreach (var entry in entries)
{
foreach (var property in entry.Properties)
{
if (property.CurrentValue is string stringValue)
{
property.CurrentValue = stringValue.Trim(); // here
}
}
}
}
}
英文:
You can achieve this by overriding the SaveChanges method of your DbContext class. In the overridden method, you can iterate through all the entities in the ChangeTracker and trim all the string properties before saving the changes to the database.
** AppDbContext.cs **
public partial class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public virtual DbSet<Company> Companies { get; set; }
... // other DbSets
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
** AppDbContextPartial.cs **
public partial class AppDbContext
{
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
TrimStringProperties();
return await base.SaveChangesAsync(cancellationToken);
}
private void TrimStringProperties()
{
var entries = ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
foreach (var entry in entries)
{
foreach (var property in entry.Properties)
{
if (property.CurrentValue is string stringValue)
{
property.CurrentValue = stringValue.Trim(); // here
}
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论