Description
openedon Jan 28, 2021
EF Core version: 5.0.2
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 5.0
Operating system: Windows 7
IDE: Visual Studio 2019 16.8
Consider we have the following entities:
public class BaseEntity
{
public int Id { get; set; }
public virtual string MyProperty { get; set; }
}
public class DerivedEntity : BaseEntity
{
private int myProperty ;
[BackingField(nameof(myProperty))]
public override string MyProperty
{
get => MyDecoder.Decode(myProperty) ;
set => myProperty = MyEncoder.Encode(value);
}
}
When we query for DerivedEntity
, we will lose MyProperty
property values. This is because the backing field of the base class is used, rather than the backing field of the derived class. Fluent api also does't work:
modelBuilder.Entity<DerivedEntity>().Property(x => x.MyProperty).HasField("myProperty");
A workaround is to use same backing field for both base and derived classes. However, it's not always possible to change the base class.
I don't know whether this is a by-design/known limitation. I don't find this in the pages:
https://docs.microsoft.com/en-us/ef/core/modeling/inheritance
https://docs.microsoft.com/en-us/ef/core/modeling/backing-field.