我被困在翻译LINQToSQL的左外部联接,该联接返回唯一的父行。

我有2个表(Project,Project_Notes,这是一个由Project_ID链接的1对多关系)。我正在2表的多个列上进行关键字搜索,并且仅当Project_Notes中的列包含关键字时才想返回唯一的项目。我有这个linqtoSQl序列,但似乎正在返回多个Project行。也许以某种方式在LINQ中执行Exist吗?或者也许是某种groupby?

这是LINQToSQL:

 query = from p in query
 join n in notes on p.PROJECT_ID equals n.PROJECT_ID into projectnotes
 from n in notes.DefaultIfEmpty()
 where n.NOTES.Contains(cwForm.search1Form)
 select p;


这是它从探查器生成的SQL


  exec sp_executesql N'SELECT [t2]。[Title],[t2]。[State],[t2]。[PROJECT_ID],
  [t2]。[PROVIDER_ID],[t2]。[CATEGORY_ID],[t2]。[城市],[t2]。[UploadedDate],
  [t2]。[SubmittedDate],[t2]。[Project_Type] FROM(SELECT ROW_NUMBER()OVER(按ORDER BY
  [t0]。[UploadedDate])AS [ROW_NUMBER],[t0]。[Title],[t0]。[State],[t0]。[PROJECT_ID],
  [t0]。[PROVIDER_ID],[t0]。[CATEGORY_ID],[t0]。[城市],[t0]。[UploadedDate],
  [t0]。[SubmittedDate],[t0]。[Project_Type]来自[dbo]。[项目] AS [t0]左外加入
  [dbo]。[PROJECT_NOTES] AS [t1]在1 = 1的位置([t1]。[NOTES]像@ p0)并且
  ([t0] .SubmittedDate]> = @ p1)AND([t0]。[SubmittedDate]   @ p3)AND([[t0]。[CATEGORY_ID]为NULL))AS [t2]在[t2]处。@ p4 + 1之间的[ROW_NUMBER]
  AND @ p4 + @ p5 ORDER BY [t2]。[ROW_NUMBER]',N'@ p0 varchar(9),@ p1 datetime,@ p2 datetime,@ p3
  int,@ p4 int,@ p5 int',@ p0 ='%chicago%',@ p1 =''2000-09-02 00:00:00:000'',@ p2 =''2009-03-02
  00:00:00:000'',@ p3 = 1000,@ p4 = 373620,@ p5 = 20


此查询在结果中返回“ 1对多”关系的所有信息。我从这里找到了如何在LINQ中执行Existshttp://www.linq-to-sql.com/linq-to-sql/t-sql-to-linq-upgrade/linq-exists/

这是使用Exists的LINQToSQL:

query = from p in query
where (from n in notes
where n.NOTES.Contains(cwForm.search1Form)
select n.PROJECT_ID).Contains(p.PROJECT_ID)
select p;


生成的SQL语句:


  exec sp_executesql N'SELECT COUNT(*)AS [value] from [dbo]。[PROJECTS] AS [t0]在哪里
  (在[dbo]中存在(从[dbo]中选择空为[空]。[PROJECT_NOTES]为[t1]的位置)
  ([t1..PROJECT_ID] =([t0]。[PROJECT_ID]))AND([t1 .. [NOTES]喜欢@ p0)))AND
  ([t0]。[SubmittedDate]> = @ p1)AND([t0]。[SubmittedDate]   @ p3)AND([t0]。[CATEGORY_ID] IS NULL)',N'@ p0 varchar(9),@ p1 datetime,@ p2 datetime,@ p3
  int',@ p0 ='%chicago%',@ p1 =''2000-09-02 00:00:00:000'',@ p2 =''2009-03-02
  00:00:00:000'',@ p3 = 1000


我从使用databind()Exists获取SQL超时。

最佳答案

它似乎正在返回多个项目行


是的,这就是联接的工作方式。如果一个项目有5个匹配的注释,它将显示5次。



如果问题出在哪里-“加入”是错误的成语!

您想要将项目筛选为注释包含某些文本的项目:

var query = db.Project
  .Where(p => p.Notes.Any(n => n.NoteField.Contains(searchString)));

关于c# - 左外部联接并存在于Linq To SQL C#.NET 3.5中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/603380/

10-12 02:09