C#LINQ to Entities查询两个不同属性的交集 [英] C# LINQ to Entities query for the intersection of two different properties

查看:129
本文介绍了C#LINQ to Entities查询两个不同属性的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


铅笔具有Pencil.Id(int)和Pencil.Colors (IEnumerable)属性



Pen 具有Pen.Id(int)和Pen.Colors(IEnumerable)属性



颜色具有Id和名称。


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



我想构建一个查询,这将显示给我一样我拿着笔的彩色铅笔。



我正在使用以下LINQ到实体查询:

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

颜色模型是IEnumerable,所以它有1种以上的颜色。例如;笔有15种不同的颜色,铅笔有25种不同的颜色。我想带上对应的铅笔,如果我拿着的笔的一种颜色也可以在那支铅笔的调色板中使用。



但是我正在使用常量变量(例如int或string而不是对象)的例外。



我该怎么办?感谢您的帮助。



EDITED:
我为下一个可能的问题创建了一个新问题: C#LINQ to Entities - 对象和收集对象

解决方案

  int id = id_of_the_pen_that_i_am_holding; 
笔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));
pre>

I have 3 models named:

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.

Pencil has a relation with colors (many-to-many) Pen has a relation with colors (many-to-many)

I want to build a query which will show me the same colored pencils for the pen that I am holding.

I am using the below LINQ-to-Entities query:

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;

Colors model is IEnumerable so it has more than 1 color. For example; the pen has 15 different colors and pencil is having 25 different colors. I want to bring the corresonding pencil if one of the colors of the pen that I am holding is also avaialable in the color palette of that pencil.

But I am getting an exception to use regular variables like int or string rather than objects.

What can I do? Thanks in advance for your helps.

EDITED: I've created a new question for a next possible issue: 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查询两个不同属性的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆