我有3个名为的模型:
拥有Pencil.Id(int)和Pencil.Colors(IEnumerable)属性的铅笔
拥有Pen.Id(int)和Pen.Colors(IEnumerable)属性的Pen
颜色拥有ID和名称。
铅笔与颜色有关(多对多) 笔与颜色(多对多)有关系
我想建立一个查询,它会向我显示我所持有的笔的彩色铅笔。
我正在使用以下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,所以它有超过1种颜色。例如;笔有15种不同的颜色,铅笔有25种不同的颜色。如果我所持有的笔的一种颜色在该铅笔的调色板中也是可用的,我想带上相应的铅笔。
但我得到一个例外,使用常规变量,如int或string而不是对象。
我该怎么办?提前感谢您的帮助。
编辑: 我为下一个可能的问题创建了一个新问题:C# LINQ to Entities- Properties on the intersection of an object and a collection of objects
答案 0 :(得分:6)
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));
答案 1 :(得分:0)
如何简化代码并以这种方式进行操作,我知道它并不是特别优雅,但我不确定(在我的头脑中)LINQ是否有很好的做法你想要的:
IList<Pencil> sameColorPencils = new List<Pencil>();
Pen p = db.Pens.Find(id);
foreach (Color color in p.Color)
{
var pencils = from pencil in db.Pencils
where pencil.Color == color
select pencil;
foreach (Pencil pencil in pencils)
{
if (sameColorPencils.Count(e => e.Id == pencil.Id) == 0)
{
sameColorPencils.Add(pencils);
}
}
}