Mapping NULLs to type default

点点圈 提交于 2021-01-07 02:32:39

问题


I have model classes that I need to use with Entity Framework Core. Unfortunately, I cannot make changes to these classes and none of them use nullable columns, while the database tables they map to do have nullable columns. EF throws an (expected) exception when trying to pull data from the database into the model class.

Is there a way to configure EF Core to automatically map NULLs in a column to the default for the given type?

For example,

//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");
        }
    }
}

The goal would be that when requesting the data a null in column Age would become the type default (0 in this case).


回答1:


If you can change the implementation of the class without changing its public definition, you can do this.

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);
        });
    }
}


来源:https://stackoverflow.com/questions/55362908/mapping-nulls-to-type-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!