在使用 Entity Framework Core 进行数据库映射时,默认情况下,null 值不会被保存到数据库。如果你想要将 null 值保存到数据库,可以使用以下两种方法:

  1. 使用可空类型(Nullable Type):将对应的属性定义为可空类型,例如使用 'int?' 代替 'int','DateTime?' 代替 'DateTime' 等。这样,当属性的值为 null 时,EF Core 会将 null 值保存到数据库。
public class YourEntity
{
    public int? SomeNullableProperty { get; set; } 
    public DateTime? AnotherNullableProperty { get; set; }
    // other properties
}
  1. 使用 'ValueConverter':通过使用 'ValueConverter',你可以自定义如何将 null 值转换为数据库中的特定值。例如,你可以将 null 值转换为空字符串或者其他特定的值。
public class YourDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<YourEntity>()
            .Property(e => e.SomeProperty)
            .HasConversion(new NullValueConverter<int>());

        modelBuilder.Entity<YourEntity>()
            .Property(e => e.AnotherProperty)
            .HasConversion(new NullValueConverter<DateTime>());
    }
}

public class NullValueConverter<T> : ValueConverter<T?, T>
where T : struct
{
    public NullValueConverter(ConverterMappingHints mappingHints = null)
        : base(
              v => v.GetValueOrDefault(),
              v => new T?(v),
              mappingHints)
    {
    }
}

使用上述方法之一,你可以将 null 值保存到数据库中。

.NET Core Entity Framework Core 映射时保存 Null 值到数据库的两种方法

原文地址: https://www.cveoy.top/t/topic/qlyi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录