2010-07-09 44 views
0

我有一個1到很多關係tblBusinesstblPhone之間。對於特定的BusinessID我試圖返回單個字符串信息綁定到文本框。以下是我的最新嘗試以及來自同一LINQ的生成的SQL。無論我嘗試過什麼,它都會返回NULL,除非所有3個字段都有值。LINQ 2 SQL返回多個爲單個字符串

我在做什麼錯?謝謝!


首先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] 

回答

1

我是一個LINQ到實體男人自己,我不知道的LINQ to SQL提供多少字符串操作支持,所以我會做字符串連接和空測試在LINQ上下文之外:

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); 

原始查詢的問題是空值傳播,所以「blah」+ NULL爲NULL。

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;