0

我正在尝试使用 Linq 查询我的数据库。简而言之,我的 linq 语句没有返回我想要的数据并且我遇到了错误。

public class Product{
        [Key]
        public int id{get;set;}
        [Required]
        [MinLength(3)]
        public string Name{get;set;}
        [MinLength(10)]
        public string Description{get;set;}
        [Required]
        [Range(0, double.MaxValue)]
        public decimal Price{get;set;}
        public DateTime CreatedAt{get;set;} = DateTime.Now;
        public DateTime UpdatedAt{get;set;} = DateTime.Now;

        public List<ProductCategory> ProductCategories{get;set;}
    }

public class Category{
        [Key]
        public int id{get;set;}
        [Required]
        [MinLength(2)]
        public string Name{get;set;}
        public DateTime CreatedAt{get;set;} = DateTime.Now;
        public DateTime UpdatedAt{get;set;} = DateTime.Now;

        public List<ProductCategory> ProductCategories{get;set;}
    }

public class ProductCategory{
        [Key]
        public int id{get;set;}
        public int ProductId{get;set;}
        public int CategoryId{get;set;}

        public Product Product{get;set;}
        public Category Category{get;set;}
    }

#Variable used in troublesome code (in controller)
Product product = context.Products
                .Include(p => p.ProductCategories)
                .ThenInclude(pc => pc.Category)
                .FirstOrDefault(p => p.id == id);

#Troublesome code (in controller)
List<Category> categories = context.Categories
                .Include(c => c.ProductCategories)
                .ThenInclude(pc => pc.Product)
                .Where(c => c.ProductCategories.Select(pc => pc.Product) != product)
                .ToList();

产品和类别具有多对多的关系。我希望类别变量包含不在检索到的产品中的所有类别的列表。有人不能引导我朝着正确的方向前进或告诉我我在这里做错了什么吗?

错误:'System.Nullable 1[System.Int32]' cannot be used as the data type for a sequence with an ItemExpression of type 'System.Nullable1 [System.Int32]'

4

1 回答 1

2

正如评论中所说,直接错误在于

c.ProductCategories.Select(pc => pc.Product) != product

因为c.ProductCategories.Select(pc => pc.Product)Products 的序列,不能与 one 进行比较Product

另一个问题是您product在第二个查询中使用。即使正确使用,例如...

List<Category> categories = context.Categories
                .Include(c => c.ProductCategories)
                .ThenInclude(pc => pc.Product)
                .Where(c => !c.ProductCategories.Select(pc => pc.Product)
                    .Any(p => p == product))
                .ToList();

...问题是product不能翻译成 SQL 和 EF 切换到客户端评估。

product(我假设您正在使用 EF-core。如果您在后续查询中这样使用,EF6 将不允许它并引发异常)。

但是有一个简单的解决方案甚至可以为您节省一次往返行程。直接使用id即可:

List<Category> categories = context.Categories
                .Include(c => c.ProductCategories)
                .ThenInclude(pc => pc.Product)
                .Where(c => !c.ProductCategories.Any(pc => pc.ProductId == id))
                .ToList();
于 2019-08-12T22:20:09.073 回答