Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow properties to use a different backing field on a derived type #24006

Open
Tracked by #240
anranruye opened this issue Jan 28, 2021 · 2 comments
Open
Tracked by #240

Allow properties to use a different backing field on a derived type #24006

anranruye opened this issue Jan 28, 2021 · 2 comments

Comments

@anranruye
Copy link

anranruye commented 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.

@ajcvickers ajcvickers changed the title Limitation: Can not individually configure overridden properties of derived entity classes Limitation: Properties are limited to a single backing field Feb 1, 2021
@ajcvickers ajcvickers added this to the Backlog milestone Feb 1, 2021
@ajcvickers
Copy link
Contributor

@anranruye Thanks for reporting this. I'm putting this on the backlog for now, but this will be non-trivial to implement and so we are only likely to do so we significantly more feedback indicating that this is important. You can instead access the property through its navigation which will produce the correct results.

@anranruye
Copy link
Author

@ajcvickers Fine.

I found this just by accident and don't really need this feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants