Reputation: 12803
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).
Upvotes: 0
Views: 1168
Reputation: 6522
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);
});
}
}
Upvotes: 2