1

我一直在翻译从 LINQToSQL 返回唯一父行的左外连接。

我有 2 个表(Project、Project_Notes,它是由 Project_ID 链接的一对多关系)。我正在对 2 表的多个列进行关键字搜索,如果 Project_Notes 中的列包含关键字,我只想返回唯一的项目。我有这个 linqtoSQl 序列,但它似乎返回多个项目行。也许以Exist某种方式在 LINQ 中做一个?或者也许是某种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].[ City], [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].[City], [t0] .[UploadedDate], [t0].[SubmittedDate], [t0].[Project_Type] FROM [dbo].[PROJECTS] AS [t0] LEFT OUTER JOIN [dbo].[PROJECT_NOTES] AS [t1] ON 1=1 WHERE ([t1].[NOTES] LIKE @p0) AND ([t0].SubmittedDate] >= @p1) AND ([t0].[SubmittedDate] < @p2) AND ([t0].[PROVIDER_ID] = @ p3) AND ([t0].[CATEGORY_ID] IS NULL)) AS [t2] WHERE [t2].[ROW_NUMBER] @p4 + 1 AND @p4 + @p5 ORDER BY [t2].[ROW_NUMBER]',N '@p0 varchar(9),@p1 日期时间,@p2 日期时间,@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 对多关系的所有复数。我从这里找到了如何Exists在 LINQ 中进行操作。http://www.linq-to-sql.com/linq-to-sql/t-sql-to-linq-upgrade/linq-exists/

这是使用的 LINQToSQL Exists

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] WHERE (EXISTS(SELECT NULL AS [EMPTY] FROM [dbo].[PROJECT_NOTES] AS [t1] WHERE ([ t1].PROJECT_ID] = ([t0].[PROJECT_ID])) AND ([t1].[NOTES] LIKE @p0))) AND ([t0].[SubmittedDate] >= @p1) AND ([t0] .[SubmittedDate] < @p2) AND ([t0].[PROVIDER_ID] = @p3) AND ([t0].[CATEGORY_ID] IS NULL)',N'@p0 varchar(9),@p1 datetime,@p2日期时间,@p3 int',@p0='%chicago%',@p1=''2000-09-02 00:00:00:000'',@p2=''2009-03-02 00:00: 00:000'',@p3=1000

databind()从使用Exists.

4

2 回答 2

5

它似乎返回多个项目行

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


如果问题是 - “加入”是错误的习语!

您想将项目过滤到那些笔记包含特定文本的项目:

var query = db.Project
  .Where(p => p.Notes.Any(n => n.NoteField.Contains(searchString)));
于 2009-03-02T18:38:17.227 回答
2

您将不得不使用 DefaultIfEmpty 扩展方法。已经有一些关于 SO 的问题显示了如何做到这一点。这是一个很好的例子:

如何在 LINQ 中执行嵌套的 Join、Add 和 Group?

于 2009-03-02T18:17:18.917 回答