我正在尝试使用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();
产品和类别具有多对多关系。我希望category变量包含检索到的产品中没有的所有类别的列表。有人不能指引我正确的方向或告诉我我在做什么错吗?
错误:
'System.Nullable 1[System.Int32]' cannot be used as the data type for a sequence with an ItemExpression of type 'System.Nullable
1 [System.Int32]'
答案 0 :(得分:2)
如评论中所述,直接错误位于
c.ProductCategories.Select(pc => pc.Product) != product
因为c.ProductCategories.Select(pc => pc.Product)
是Product
的序列,所以不能与一个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无法切换到客户端评估。
(我假设您使用的是EF-core。如果您在后续查询中使用product
,则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();