【问题标题】:Mapping NULLs to type default将 NULL 映射到类型默认值
【发布时间】:2019-08-17 04:13:59
【问题描述】:

我有需要与 Entity Framework Core 一起使用的模型类。不幸的是,我无法对这些类进行更改,并且它们都没有使用可为空的列,而它们映射到的数据库表确实具有可为空的列。 EF 在尝试将数据从数据库拉入模型类时抛出(预期的)异常。

有没有办法将 EF Core 配置为自动将列中的 NULL 映射到给定类型的默认值?

例如,

//Model class
class Foo
{
    public int Id {get; set;}
    public int Age {get; set;}
}

//DbContext
public class MyContext: DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    { 
        modelBuilder.Entity<MyContext>(entity =>
        {
            entity.HasKey(e => new { e.Id });
            entity.ToTable("Foo", "dbo");
            entity.Property(e => e.Age).HasColumnName("Age");
        }
    }
}

目标是在请求数据时,Age 列中的 null 将成为默认类型(在本例中为 0)。

【问题讨论】:

标签: .net mapping entity-framework-core


【解决方案1】:

如果你可以改变类的实现不改变它的公共定义,你可以这样做.

public class Foo
{
    public int Id { get; set; }
    private int? _Age { get; set; }
    public int Age
    {
        get => _Age.GetValueOrDefault();
        set => _Age = value;
    }
}

public class MyContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foo>(entity =>
        {
            entity.Property("_Age").HasColumnName("Age");
            entity.Ignore(e => e.Age);
        });
    }
}

【讨论】:

  • 这是一个很好的解决方案。感谢您的考虑!
  • 不客气!您可能还想投票github.com/aspnet/EntityFrameworkCore/issues/13850,这是一个更好的解决方案。 :)
  • 小心,因为这可能会破坏您退出的查询。例如dbContext.Foos.OrderBy(f =&gt; f.Age).ToArray() 将不起作用。
猜你喜欢
  • 2018-01-03
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2015-02-21
相关资源
最近更新 更多