gpt4 book ai didi

C# LINQ to Entities 查询两个不同属性的交集

转载 作者:太空狗 更新时间:2023-10-29 23:09:28 24 4
gpt4 key购买 nike

我有 3 个模型命名为:

Pencil having Pencil.Id(int) and Pencil.Colors(IEnumerable) Property

Pen having Pen.Id(int) and Pen.Colors(IEnumerable) Property

Colors having Id and name.

铅笔与颜色有关系(多对多)笔与颜色的关系(多对多)

我想构建一个查询,它会显示与我所持笔相同颜色的铅笔。

我正在使用以下 LINQ-to-Entities 查询:

int id = id_of_the_pen_that_i_am_holding;
Pen p = db.Pens.Find(id);
var list = from m in db.Pencils where m.Colors.Intersect(p.Colors) != null select m;

颜色模型是 IEnumerable,所以它有不止一种颜色。例如;钢笔有 15 种不同的颜色,而铅笔有 25 种不同的颜色。如果我所持笔的其中一种颜色在该铅笔的调色板中也可用,我想带上相应的铅笔。

但是我遇到了一个异常(exception),即使用 int 或 string 等常规变量而不是对象。

我能做什么?预先感谢您的帮助。

已编辑:我为下一个可能的问题创建了一个新问题:C# LINQ to Entities- Properties on the intersection of an object and a collection of objects

最佳答案

int id = id_of_the_pen_that_i_am_holding;
Pen p = db.Pens.Find(id);
var penColorIds = p.Color.Select(m => m.Id).ToList();
var list = db.Pencils.Where(pencil => pencil.Color.Any(color => penColorIds.Contains(color.Id));

关于C# LINQ to Entities 查询两个不同属性的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11722084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com