简体   繁体   中英

EF Core backing field with filter on property

Consider the following

public class Order
{
    private readonly List<OrderLineItem> lineItems = new();  
    public IReadOnlyCollection<OrderLineItem> LineItems => lineItems;
}

and in the DbContext mapper

builder.HasMany(u => u.LineItems).WithOne().HasForeignKey(u => u.ProviderOrderId);
builder.Metadata.FindNavigation(nameof(ProviderOrder.LineItems))!.SetPropertyAccessMode(PropertyAccessMode.Field);

I want to add a filter to the LineItems property like this

public IReadOnlyCollection<OrderLineItem> LineItems => new ReadOnlyCollection<OrderLineItem>(lineItems.Where(u => !u.IsDeleted).ToList())

Can this potentially have any impact on the data that is being saved (ie accidentally filtering out the "soft" deleted records and deleting them permanently)?

From my understanding EF Core will only read to and from the backing field exclusively, and the property is only for setting up the initial mapping, and also for public access to the data.

Googling for people doing similar things didn't bring much up, so this is a sense check essentially.

Thanks for easing my mind.

Through my own testing, I'm now satisfied that it's perfectly fine to apply filters to the property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM