我在EF Core上遇到了一个罕见的问题。
这是我的方法:
public async Task<Tuple<List<ProductDto>, int>> GetFilteredAsync(MainFilter filter)
{
var filteredQuery = _repository.GetAll();
if (filter.Active)
filteredQuery = filteredQuery.Where(p => p.Active);
filteredQuery = filteredQuery.Where(p => p.ProductAvailableDates.Any(pad => pad.Date.CompareDateWihtoutTime(filter.AvailableFrom) >= 0));
if (filter.AvailableTo.HasValue)
{
filteredQuery = filteredQuery.Where(p => p.ProductAvailableDates.Any(pad => pad.Date.CompareDateWihtoutTime(filter.AvailableTo.Value) <= 0));
}
if (!string.IsNullOrEmpty(filter.City))
{
filteredQuery = filteredQuery.Where(p => p.City.Equals(filter.City));
}
if (filter.CategoryId.HasValue)
{
filteredQuery = filteredQuery.Where(p => p.CategoryProducts.Any(cp => cp.CategoryId == filter.CategoryId.Value));
}
if (!string.IsNullOrEmpty(filter.NameSubset))
filteredQuery = filteredQuery.Where(p => p.Name.Contains(filter.NameSubset));
if (filter.PriceHigherThan.HasValue)
filteredQuery = filteredQuery.Where(p => p.Price > filter.PriceHigherThan);
if (filter.PriceLowerThan.HasValue)
filteredQuery = filteredQuery.Where(p => p.Price < filter.PriceLowerThan);
if (filter.UserId.HasValue)
filteredQuery = filteredQuery.Where(p => p.OwnerId.Equals(filter.UserId));
filteredQuery = filteredQuery.Include(x => x.ProductImages);
var numberOfEntities = filteredQuery.Count();
// order items
switch (filter.OrderItem)
{
case "name":
filteredQuery = filteredQuery.OrderByAscOrDesc(filter.Ascending, x => x.Name);
break;
case "price":
filteredQuery = filteredQuery.OrderByAscOrDesc(filter.Ascending, x => x.Price);
break;
case "creation_time":
filteredQuery = filteredQuery.OrderByAscOrDesc(filter.Ascending, x => x.CreatedAt);
break;
}
filteredQuery = filteredQuery.Paginate(filter);
var filteredList = await filteredQuery.ToListAsync();
var dtoList = await ConvertModelListToDtoList(filteredList);
return new Tuple<List<ProductDto>, int>(dtoList, numberOfEntities);
}
根据过滤器参数过滤我的产品(可以正常工作),但是我的实体“产品”丢失了他的分类数据,例如:imagesUrls和ProductAvailableDate。调用方法repository.getAll时,该方法可用并返回,但是当我的查询被过滤且与产品相关的实体迷路时,有2种产品(其中有1个以上的imageUrl)丢失了问题,但是对于第3个产品和最后一个产品,一切都很好
产品实体:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public List<CategoryProduct> CategoryProducts { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public string City { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? DeactivetedAt { get; set; }
public Guid OwnerId { get; set; }
public List<ProductImage> ProductImages { get; set; }
public List<ProductAvailableDate> ProductAvailableDates { get; set; }
.Include()
在这里无济于事。