首页 > 解决方案 > 将实体框架数据库中的所有字符串设为大写

问题描述

这是一个假设或“这可能吗?” 问题。

我在 ASP.Net Core 2.2 MVC 中使用实体框架。有没有办法让来自数据库的所有字符串都变成大写?我不想将它们存储为大写,我只想在检索它们时将它们设为大写。

最好,我希望它在我的代码中仅占一个位置,而不是在模型属性上编写一堆“getter”。

标签: asp.net-core.net-coreentity-framework-core

解决方案


对于解决方法,您可以尝试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);
                }
            }
        }
    }
}

推荐阅读