当我尝试筛选我的值对象属性时,LINQ表达式无法转换

h5qlskok  于 2023-09-28  发布在  其他
关注(0)|答案(1)|浏览(126)

我在过滤查询时遇到问题。这是我的查询:

  1. var products = _context.Products.Select(x => new GetProductsDto {
  2. Id = x.Id,
  3. Name = x.Name.Value,
  4. Quantity = x.Quantity.Value,
  5. Brand = x.Brand,
  6. Displayed = x.Displayed,
  7. Price = x.Price,
  8. Category = x.Category.Name.Value
  9. });
  10. products = products.Where(p => p.Name.Contains(request.SearchKey));

这是我的产品实体:

  1. public class Product{
  2. public Name Name { get; private set; }
  3. public Quantity Quantity { get; private set; }
  4. public string Brand { get; private set; }
  5. public string Description { get; private set; }
  6. public int Price { get; private set; }
  7. public bool Displayed { get; private set; }
  8. public int CategoryId { get; set; }
  9. public virtual Category Category { get; set; }
  10. public virtual ICollection<ProductImage> ProductImages { get; private set; }
  11. public virtual ICollection<ProductFeature> ProductFeatures { get; private set; }
  12. }

My Name ValueObject:

  1. public class Name : ValueObject
  2. {
  3. public const byte MaxLen = 100;
  4. public string Value { get; private set; }
  5. private Name()
  6. {
  7. }
  8. public static Name Create(string name)
  9. {
  10. var shopName = new Name();
  11. if (name.Length > MaxLen)
  12. {
  13. shopName.Result.WithError(
  14. string.Format(Validations.MaxLenValidation, DataDictionary.ShopName, MaxLen));
  15. return shopName;
  16. }
  17. shopName.Value = name;
  18. return shopName;
  19. }
  20. }

这是我的产品实体Map到数据库:

  1. internal class ProductEntityMap : IEntityTypeConfiguration<Product>
  2. {
  3. public void Configure(EntityTypeBuilder<Product> builder)
  4. {
  5. builder.HasKey( x => x.Id);
  6. builder.Property(x => x.Id)
  7. .ValueGeneratedOnAdd();
  8. builder.Property(x => x.Quantity)
  9. .HasConversion(x => x.Value,
  10. x => Domain.Aggregates.Products.ValueObjects.Quantity.Create(x));
  11. builder.Property(x => x.Name)
  12. .HasConversion(x => x.Value,
  13. x => Domain.SharedKernel.Name.Create(x));
  14. }
  15. }

我认为错误是因为我在实体中使用了'Name' valueObject。请帮我

guykilcj

guykilcj1#

最后我找到了解决办法。我将这一行添加到我的ValueObject类中,例如在我的Name ValueObject类中,它是这样的:

  1. public static explicit operator string(Name name) => name.Value;

我改变了我的查询如下:

  1. var shops = _context.Shops.AsQueryable();
  2. if (searchKey is not null)
  3. shops = shops
  4. .Where(x => ((string)x.Name).ToLower().Contains(searchKey.ToLower()));

最后,我检查了SQL Server Profiler工具,以确保查询在服务器而不是客户端执行。

相关问题