I do not know why I am getting this error:
InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning': An attempt was made to lazy-load navigation 'PerformedServices' on a detached entity of type 'OrderProxy'. Lazy loading is not supported for detached entities or entities that are loaded with 'AsNoTracking'. This exception can be suppressed or logged by passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
I don't use 'AsNoTracking' method or anything else. I'm just trying to handle CollectionChanged
event of PerformedServices
property:
// ObservableObject implements INotifyPropertyChanged
public class Order : ObservableObject
{
public Order()
{
// I'm getting error here
PerformedServices.CollectionChanged = PerformedServices_CollectionChanged;
}
private void PerformedServices_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (INotifyPropertyChanged item in e.NewItems)
item.PropertyChanged = PerformedServicesItem_PropertyChanged;
if (e.OldItems != null)
foreach (INotifyPropertyChanged item in e.OldItems)
item.PropertyChanged -= PerformedServicesItem_PropertyChanged;
}
private void PerformedServicesItem_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
var ps = (PerformedServices?)sender;
if (e.PropertyName == nameof(ps.SummaryPrice))
OnPropertyChanged(nameof(OrderTotalPrice));
}
public int Id { get; set; }
public int ClientId { get; set; }
public virtual Client? Client { get; set; }
public DateTime CompleteDate { get; set; }
public virtual ObservableCollection<Service> Services { get; set; } = new();
public virtual ObservableCollection<PerformedServices> PerformedServices { get; set; } = new();
public int OrderTotalPrice => PerformedServices.Sum(ps => ps.SummaryPrice);
}
I don't have any ideas to fix this problem. All my search attempts did not lead to clear answers.
In fact, I would just like to get a calculated property that would calculate the sum of the prices of all services in the order, and notify about the update when the total price for any service changes. Maybe there is some better way to do this?
CodePudding user response:
Virtual collections are lazy loaded. You should force eager loading instead. If the terms are new to you then you should read up more about entity Framework.
Start here.
It is a bad idea to directly present objects from entity Framework to the ui you should instead use automapper or something similar to copy data out your entity Framework object map into viewmodels.
Setting an item in an observable collection to itself will raise notification on that item and is arguably more elegant than what you sent to be trying to do in some of your code there.