映射NULL以键入default [英] Mapping NULLs to type default

查看:49
本文介绍了映射NULL以键入default的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些需要与Entity Framework Core一起使用的模型类.不幸的是,我无法更改这些类,并且它们都没有使用可为空的列,而它们映射为的数据库表却具有可为空的列.尝试从数据库中将数据拉入模型类时,EF引发(预期)异常.

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.

是否可以将EF Core配置为自动将列中的NULL映射为给定类型的默认值?

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

例如,

//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).

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

推荐答案

如果您可以更改该类的实现而无需更改,公开的定义,您可以执行此操作.

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

这篇关于映射NULL以键入default的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆