Linq to SQL 使用 IQueryable API 实现一对多关系
假设A是一个父表,有很多B记录。本质上,我需要 LINQ to SQL 来生成此查询:
Select * from A
Join B n on B.Id = A.Id
where A.OtherId in (0,1,2,3)
and B.DateTime >= '2011-02-03 00:30:00.000'
and A.TypeId = 1
order by B.DateTime
我的 LINQ 如下所示:
List<string> programIds = new List<string>("0", "1", "2", "3");
IQueryable<A> query = db.As;
query = query.Where(a => programIds.Contains(a.ProgramId));
query = query.Where(a => a.B.Any(b => b.DateTime >= ('2011-02-03 00:30:00.000')));
问题从最后一条语句开始,生成的查询如下所示:
?query
{SELECT *
FROM [dbo].[A] AS [A]
WHERE (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[B] AS [B]
WHERE ([B].[AirsOnStartDateTime] >= @p0) AND ([B].[Id] = [A].[Id])
)) AND ((CONVERT(BigInt,[A].[OtherId])) IN (@p1, @p2, @p3, @p4))
}
有什么想法吗?
Assume A is a parent table with many B records. Essentially I need LINQ to SQL to generate this query:
Select * from A
Join B n on B.Id = A.Id
where A.OtherId in (0,1,2,3)
and B.DateTime >= '2011-02-03 00:30:00.000'
and A.TypeId = 1
order by B.DateTime
The LINQ I have looks like this:
List<string> programIds = new List<string>("0", "1", "2", "3");
IQueryable<A> query = db.As;
query = query.Where(a => programIds.Contains(a.ProgramId));
query = query.Where(a => a.B.Any(b => b.DateTime >= ('2011-02-03 00:30:00.000')));
The problem begins on this last statement, the generated query then looks like this:
?query
{SELECT *
FROM [dbo].[A] AS [A]
WHERE (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[B] AS [B]
WHERE ([B].[AirsOnStartDateTime] >= @p0) AND ([B].[Id] = [A].[Id])
)) AND ((CONVERT(BigInt,[A].[OtherId])) IN (@p1, @p2, @p3, @p4))
}
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
抱歉,我正在记事本中输入此内容,目前无法验证语法,但我认为您正在寻找类似的内容:
只需在匿名类型选择部分中填写您想要返回的字段即可。
另外,我假设 db.Bs 是从表中获取 B 值的方法...适当修复该问题。
Sorry, I'm typing this up in notepad and can't verify the syntax at the moment, but I think something like this is what you are looking for:
Just fill in the fields you want to return in the anonymous type select section.
Also, I made an assumption on the db.Bs being the way to get the B values out of your table... Fix that as appropriate.