TheKemo
TheKemo
CC#
Created by TheKemo on 7/9/2024 in #help
Calculated Properties with EF Core
Hi everyone, I'm facing an issue with loading and calculating projected properties in my Entity Framework Core project using the EntityFramework.Projectables library. Here's the situation: I have a Product class with various properties and related entities, and each Product has a ProductMetrics class with several projectable properties. When I fetch a product using projection and map the properties, the values are correctly calculated. However, if I simply fetch all product entities, the values aren't calculated.
List<Product> products = await _productRepository.Query
.Include(x => x.Batches.Where(b => b.Active && batchesId.Contains(b.Id)))
.ThenInclude(x => x.Navigation.DocumentLine)
//.Include(x => x.StockMovements)
.Include(x => x.Metrics)
.Where(x => x.Active && productsId.Contains(x.Id))
.ToListAsync(cancellationToken);
List<Product> products = await _productRepository.Query
.Include(x => x.Batches.Where(b => b.Active && batchesId.Contains(b.Id)))
.ThenInclude(x => x.Navigation.DocumentLine)
//.Include(x => x.StockMovements)
.Include(x => x.Metrics)
.Where(x => x.Active && productsId.Contains(x.Id))
.ToListAsync(cancellationToken);
Example of Calculated Property in ProductMetrics
[Projectable]
public decimal LastCostPrice => Product.GetLastCostPrice();
[Projectable]
public decimal LastCostPrice => Product.GetLastCostPrice();
Product Extension where the Calculated Method is Implemented
[Projectable]
public static decimal GetLastCostPrice(this Product product) => product.StockMovements.Where(x => x.MovementCode < 50).OrderByDescending(x => x.CreatedAt).Select(x => x.UnitCost.GetValueOrDefault(0)).FirstOrDefault();
[Projectable]
public static decimal GetLastCostPrice(this Product product) => product.StockMovements.Where(x => x.MovementCode < 50).OrderByDescending(x => x.CreatedAt).Select(x => x.UnitCost.GetValueOrDefault(0)).FirstOrDefault();
In the LINQ query, if I explicitly include the StockMovements list, the values are calculated, but this results in fetching a large number of records, making the query slow and heavy. When I fetch using AutoMapper, for example, it works great, but in this case, I want the ChangeTracker to track the Product entity. Can anyone provide any expertise on this matter to guide me or tell me what I'm doing wrong? Thanks in advance!
16 replies