我在tblBusiness
和tblPhone
之间有 1对多数关系。对于特定的BusinessID
我试图返回单个字符串信息以绑定到文本框。下面是我的最新尝试以及来自同一LINQ的Generated 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]
答案 0 :(得分:1)
我自己是LINQ to Entities的人,我不确定LINQ to SQL提供程序支持多少字符串操作,所以我会在LINQ上下文之外进行字符串连接和null测试:
var business = from businesse in context.tblBusinesses
where businesse.BusinessID == businessID
select new
{
businesse.BusinessName,
businesse.ContactName,
Phone = businesse.tblPhones.Select(p=>p.PhoneNumber)
.FirstOrDefault() ?? string.Empty
}.Single();
return (business.BusinessName ?? string.Empty) +
(business.ContactName ?? string.Empty) +
(business.Phone ?? string.Empty);
原始查询的问题是nulls propogate,所以“blah”+ NULL为NULL。
答案 1 :(得分:0)
我们试过了吗?
var business = from businesse in context.tblBusinesses
where businesse.BusinessID == businessID
select (businesse.BusinessName ?? string.Empty)
+ (businesse.ContactName ?? string.Empty)
+ (businesse.tblPhones.Select(p=>p.PhoneNumber)
.FirstOrDefault()
?? string.Empty);
当然,我真的应该问,“你究竟是在追求什么?”三个电话号码连在一起?第一个非空的?对于后者,请尝试:
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;