asp.net-core - 将实体框架数据库中的所有字符串设为大写
问题描述
这是一个假设或“这可能吗?” 问题。
我在 ASP.Net Core 2.2 MVC 中使用实体框架。有没有办法让来自数据库的所有字符串都变成大写?我不想将它们存储为大写,我只想在检索它们时将它们设为大写。
最好,我希望它在我的代码中仅占一个位置,而不是在模型属性上编写一堆“getter”。
解决方案
对于解决方法,您可以尝试HasConversion
通过循环模型和属性来配置。
尝试如下代码:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
var converter = new ValueConverter<string, string>(
v => v,
v => v.ToUpper());
foreach (var entityType in builder.Model.GetEntityTypes())
{
foreach (var property in entityType.GetProperties())
{
if (property.ClrType == typeof(string))
{
builder.Entity(entityType.Name)
.Property(property.Name)
.HasConversion(converter);
}
}
}
}
}
推荐阅读
- assembly - 在 6502 组件中绘制位图
- python - 使用 F2PY 创建 Fortran 扩展模块,自定义签名文件和子例程存储在单独的 Fortran 文件中?
- mysql - 关于从列中删除数据的mysql查询问题
- azure - 日志分析用户定义函数返回“可调用表达式的主体不能为空”
- oracle-jet - 在 OJET 中使用行数据作为列标题创建动态表
- ruby - 如何在数组 ruby 中添加元素?
- javascript - Javascript 中的 if 语句中的大于和小于
- c - 我可以从内存中加载带有 dlsym 的符号吗
- python - 我如何从视觉工作室中删除这条线
- excel - 集成文件夹选择器