LINQ 2 SQL 将多个返回为单个字符串
我在 tblBusiness
和 tblPhone
之间存在一对多关系。对于特定的 BusinessID,我尝试返回单个信息字符串以绑定到文本框。下面是我的最新尝试以及从同一 LINQ 生成的 SQL。无论我尝试什么,它都会返回 NULL
,除非所有 3 个字段都有值。
我做错了什么?谢谢!
首先是 LINQ:
using (var context = ConnectDataContext.Create())
{
context.Log = Console.Out;
var business = from businesse in context.tblBusinesses
where businesse.BusinessID == businessID
select businesse.BusinessName
+ businesse.ContactName
+ businesse.tblPhones.Select(p=>p.PhoneNumber)
.FirstOrDefault()
?? string.Empty;
return business.Single();
}
现在是 SQL:
SELECT [t2].[value]
FROM (
SELECT COALESCE(([t0].[BusinessName] + [t0].[ContactName]) + ((
SELECT TOP (1) [t1].[PhoneNumber]
FROM [dbo].[tblPhone] AS [t1]
WHERE [t1].[BusinessID] = [t0].[BusinessID]
)),@p0) AS [value], [t0].[BusinessID]
FROM [dbo].[tblBusiness] AS [t0]
) AS [t2]
WHERE [t2].[BusinessID] = @p1
-- @p0: Input NVarChar (Size = 1; Prec = 0; Scale = 0) [ ]
-- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [118]
I have a 1 to Many relationship between tblBusiness
and tblPhone
. For a specific BusinessID
I am trying to return a single string of information to bind to a textbox. Below is my latest attempt along with the Generated SQL from that same LINQ. No matter WHAT I have tried it returns NULL
unless there is a value for all 3 fields.
What am I doing wrong? Thanks!
First the LINQ:
using (var context = ConnectDataContext.Create())
{
context.Log = Console.Out;
var business = from businesse in context.tblBusinesses
where businesse.BusinessID == businessID
select businesse.BusinessName
+ businesse.ContactName
+ businesse.tblPhones.Select(p=>p.PhoneNumber)
.FirstOrDefault()
?? string.Empty;
return business.Single();
}
Now the SQL:
SELECT [t2].[value]
FROM (
SELECT COALESCE(([t0].[BusinessName] + [t0].[ContactName]) + ((
SELECT TOP (1) [t1].[PhoneNumber]
FROM [dbo].[tblPhone] AS [t1]
WHERE [t1].[BusinessID] = [t0].[BusinessID]
)),@p0) AS [value], [t0].[BusinessID]
FROM [dbo].[tblBusiness] AS [t0]
) AS [t2]
WHERE [t2].[BusinessID] = @p1
-- @p0: Input NVarChar (Size = 1; Prec = 0; Scale = 0) [ ]
-- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [118]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我自己是 LINQ to Entities 人员,并且不确定 LINQ to SQL 提供程序支持多少字符串操作,因此我会在 LINQ 上下文之外进行字符串连接和空测试:
原始查询的问题是空值传播,所以“blah”+ NULL 是 NULL。
I'm a LINQ to Entities man myself, and I'm not sure how much string manipulation the LINQ to SQL provider supports, so I would do the string concatenation and null testing outside of the LINQ context:
The problem with the original query is that nulls propogate, so "blah" + NULL is NULL.
我们是否尝试过:
当然,我真的应该问,“你到底在追求什么?”。三个电话号码串联在一起?其中第一个非空?对于后者,请尝试:
Have we tried:
Of course, I really should ask, "what exactly are you after?". The three phone number concatenated together? The first of thoses that non-null? For the latter, try: