我在查询语法中编写了以下代码,它工作正常。以下代码中的所有属性都是我的模型类中的布尔属性,并且具有0或1值。
var isTrue = (from x in _context.Fruit
join y in _context.Taste on x.Id equals y.Id
join z in color on x.Id equals z.JobId
where (x.Id == y.Id)
select x.prop1 && x. prop2 && x. prop3
&& y. prop4 && y. prop5 && y. prop6 && y. prop7
&& y. prop8 && y. prop8 && y. prop9
&& y. prop9 && y. prop10 && y. prop11
&& y. prop12 && y. prop13 && y. prop14
&& z.prop13 && z.prop14).FirstOrDefault();
但是我需要使用方法语法编写这个linq查询。 任何提示请..
答案 0 :(得分:1)
为了做到这一点,你需要使用Join
- LINQ-Method两次来构建两个元组,其中最后一个元组是从第一个元组创建的。第一个元组包含Fruit
和Taste
的元素对。我们称之为fruitTasteTuple
。第二个Join
将创建另一个元组,其中包含之前创建的第一个元组(fruitTasteTuple
)的两个元组元素的对,以及color
的元素。这个元组我叫fruitTasteColorTuple
。
为了使这更容易理解:在第二个Join
我创建了第一个元组枚举和颜色枚举的元组对。为了更好的使用,我已经将第一个元组打包到第二个元组中。
方法链版本应为:
_context.Fruit.Join(_context.Taste, x => x.Id, y => y.Id, (x, y) => new { x, y })
.Join(color, fruitTasteTuple => fruitTasteTuple.x.Id, z => z.JobId, (fruitTasteTuple, z) => new { fruitTasteTuple.x, fruitTasteTuple.y, z })
.Select(fruitTasteColorTuple =>
fruitTasteColorTuple.x.prop1 &&
fruitTasteColorTuple.x.prop2 &&
fruitTasteColorTuple.x.prop3 &&
fruitTasteColorTuple.y.prop4 &&
fruitTasteColorTuple.y.prop5 &&
fruitTasteColorTuple.y.prop6 &&
fruitTasteColorTuple.y.prop7 &&
fruitTasteColorTuple.y.prop8 &&
fruitTasteColorTuple.y.prop8 &&
fruitTasteColorTuple.y.prop9 &&
fruitTasteColorTuple.y.prop9 &&
fruitTasteColorTuple.y.prop10 &&
fruitTasteColorTuple.y.prop11 &&
fruitTasteColorTuple.y.prop12 &&
fruitTasteColorTuple.y.prop13 &&
fruitTasteColorTuple.y.prop14 &&
fruitTasteColorTuple.z.prop13 &&
fruitTasteColorTuple.z.prop14)
.FirstOrDefault();
此处Where
不会发生,因为其目的应由Join
方法处理。
答案 1 :(得分:0)
以这种方式写作或反过来没有区别。编译器总是在方法表达式(称为lambda)中编译它,如下所示:
_context.Fruit.Join(_context.Taste, i => i.Id, i => i.Id,
(fruit,taste) => new { Condition = fruit.prop1 && ... })
.FirstOrDefault();
根据评论部分的要求,第3个表的连接可以写成如下
_context.Fruit.Join(_context.Taste, i => i.Id, i => i.Id,
(fruit,taste) => new { Taste = taste, Fruit = fruit })
.Join(_context.Color, i => i.Id, i => i.Fruit.ColorId,
(f, color) => new { f.Taste, f.Fruit, Color = color})
.FirstOrDefault();
答案 2 :(得分:0)
在您的查询中,您无法使用z(未定义),但是(使用Resharper的强大功能)您可以执行以下操作:
var isTrue = (_context.Fruit.Join(_context.Taste, x => x.Id, y => y.Id, (x, y) => new {x, y})
.Where(t => (t.x.Id == t.y.Id))
.Select(
t =>
t.x.prop1 && t.x.prop2 && t.x.prop3 && t.y.prop4 && t.y.prop5 && t.y.prop6 && t.y.prop7 &&
t.y.prop8 && t.y.prop8 && t.y.prop9 && t.y.prop9 && t.y.prop10 && t.y.prop11)).FirstOrDefault();