简体   繁体   English

如何将Linq转换为sql?

[英]How To Convert Linq To Sql?

I want write code for table, I know in SQL Server, but I don't know Linq or EF. 我想在SQL Server中为表编写代码,但是我不知道Linq或EF。

SQL Server code: SQL Server代码:

SELECT *
FROM Driver
WHERE id IN (SELECT Driver
             FROM Drive_Car
             WHERE Drive_Car.Finish_Date IS NOT NULL)

I wrote this code in EF but it does not match the SQL Server results: 我在EF中编写了此代码,但与SQL Server结果不匹配:

var drivers = db.Drivers
                .Where(d => db.Drive_Car
                              .Where(dc => dc.Driver == d.ID && dc.Finish_Date != null)
                              .Select(dc => dc.Driver)
                              .Contains(d.ID));

This should be enough: 这应该足够了:

var drivers = db.Drivers
                .Where(d => db.Drive_Car
                              .Any(dc => dc.Driver == d.ID && dc.Finish_Date != null));

This leads to Exists , which is in the end about the same as the IN approach. 这将导致Exists ,最终与IN方法相同。 Duplicating rows through join and uniquifing them back through distinct is not always optimized away and you may end up with more overhead than necessary, so I would not prefer that way. 通过join复制行并通过distinct唯一化它们并不会总是被优化,并且最终可能会导致不必要的开销,因此我不喜欢这种方式。

You can get the same result using a Join operation. 您可以使用Join操作获得相同的结果。 Or to split the command into 2 parts. 或将命令分为两部分。

Linq SQL-Like syntax: Linq SQL-like语法:

var query =
   (from d in db.Driver
   join dc in dc.Drive_Car on dc.Driver equals d.ID
   where dc.Finish_Date != null
   select d).Distinct();

Other method (Split into 2 parts) 其他方法(分为2部分)

var lst =
   (from dc in dc.Drive_Car 
   where dc.Finish_Date != null
   select dc.Driver).Distinct().ToList();

var query =
   (from d in db.Driver
    where lst.Contains(d.ID)
   select d);

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM