Core Object Structure: The setter property is never called (Encapsulation Violation?)

In both EF Core and EF6, calling the getter of the Date property (see below) gives the correct value, but note the slight difference between them: in EF Core, the setter is never called!

This is my model:

public class MyModel
{      
    private DateTime _Date;
    private bool dateTimeHasBeenSet = false;
    public DateTime Date
    {
        get
        {
            return _Date;
        }
        set
        {
            dateTimeHasBeenSet = true;
            _Date = value;
        }
    }
}

This is my way to get one element:

        //Entity Framework 6
        using (Ef6Context context = new Ef6Context())
        {

            var m =  context.MyModels.First();

            // m.dateTimeHasBeenSet is true

        }

        //Entity Framework Core
        using (EfCoreContext context = new EfCoreContext())
        {

            var m = context.MyModels.First();
            // m.dateTimeHasBeenSet is false
        }

Is EF-core initializing a backup field instead of a property (via reflection)? Doesn't that break encapsulation?

I am moving some code from EF6 to EF Core, and I really would like to avoid wasting time manually accessing the logic for each setter ...

EDIT:. , - , _Property , _PropertyX ( _DateX), EF Core!

+4
1

EF Core Backing Fields:

EF / , .

EF , . , , EF , , ( readonly), .

, EF Core , ( Fluent API):

modelBuilder.Entity<MyModel>()
    .Property(b => b.Date)
    .HasField("_Date")
    .UsePropertyAccessMode(PropertyAccessMode.Property);

Backing Fields, .

, UsePropertyAccessMode ModelBuilder, :

modelBuilder.UsePropertyAccessMode(PropertyAccessMode.Property);
+3

Source: https://habr.com/ru/post/1689541/


All Articles