You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 5配合SQLite时Guid值大写存储,如何修改为小写存储?

解决方案

完全可以修改,EF Core 允许通过值转换器自定义数据类型到数据库存储格式的映射,你只需要新增Guid到小写字符串的转换规则即可。

方案1:单独为指定Guid字段配置(仅Contact的Id字段生效)

修改你的ContactConfig类中Id属性的配置,新增HasConversion规则:

public class ContactConfig : IEntityTypeConfiguration<Contact>
{
    public void Configure(EntityTypeBuilder<Contact> builder)
    {
        builder.HasKey(contact => contact.Id);
        builder.Property(contact => contact.Id)
            .IsRequired()
            .ValueGeneratedOnAdd()
            // 新增转换逻辑:存库时转小写字符串,读取时转回Guid类型
            .HasConversion(
                guid => guid.ToString().ToLowerInvariant(),
                str => Guid.Parse(str)
            );
        builder.HasMany(contact => contact.Addresses);
        builder.HasData(new Contact
            {
                Id        = Guid.NewGuid(),
                Addresses = new List<Address>(),
                FirstName = "Max",
                LastName  = "Mayer"
            });
    }
}

方案2:全局配置所有Guid字段默认小写存储(推荐,适配你全库统一格式的需求)

直接在DbContext的OnModelCreating方法中添加批量转换规则,所有实体的Guid/可空Guid类型字段都会自动转小写存库:

protected override void OnModelCreating(ModelBuilder builder)
{
    // 批量配置所有Guid类型属性的存储转换规则
    foreach (var entity in builder.Model.GetEntityTypes())
    {
        foreach (var property in entity.GetProperties())
        {
            // 处理非空Guid
            if (property.ClrType == typeof(Guid))
            {
                property.SetValueConverter(new ValueConverter<Guid, string>(
                    v => v.ToString().ToLowerInvariant(),
                    v => Guid.Parse(v)
                ));
            }
            // 处理可空Guid,不需要可以删除这部分
            if (property.ClrType == typeof(Guid?))
            {
                property.SetValueConverter(new ValueConverter<Guid?, string>(
                    v => v.HasValue ? v.Value.ToString().ToLowerInvariant() : null,
                    v => string.IsNullOrEmpty(v) ? null : Guid.Parse(v)
                ));
            }
        }
    }

    builder.ApplyConfiguration(new AddressConfig());
    builder.ApplyConfiguration(new ContactConfig());
}

注意事项

  1. 配置修改完成后需要重新生成迁移文件,更新数据库后规则才会生效
  2. 数据库中已存在的大写Guid数据需要手动批量转换为小写,避免大小写敏感场景下查询匹配失败
  3. 业务代码无需修改,依旧可以直接使用Guid类型赋值、查询,转换器会自动完成读写的格式转换

内容的提问来源于stack exchange,提问作者Marcus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:54:01