2014-12-01 40 views
-3

我想查詢一個數據庫並將兩列連接爲一個字符串,是否有一個簡單的方法做到這一點?在SQL查詢C中連接字符串#

public ActionResult GetContactList (int? id) 
{ 
    var contacts = (from ofg in db.Contacts 
        where ((ofg.ContactId == id) && (ofg.Deleted == false)) 
        select new 
         { 
          (ofg.FirstName + ofg.Surname as ofg.FullName), 
          ofg.ContactID 
         }).OrderBy(ofg => ofg.FirstName); 

    return this.Direct(contacts.ToArray()); 
} 
+6

你的例子工作嗎?如果不是什麼例外,你會得到什麼?爲什麼在數據庫中這樣做,而不是通過代碼? – ChrFin 2014-12-01 15:27:40

回答

2

在這種情況下創建一個新的匿名對象可能會看起來更像是這樣的:

select new { FullName = ofg.FirstName + ofg.Surname, ContactID = ofg.ContactID } 

注然後這是行不通的:

OrderBy(ofg => ofg.FirstName) 

因爲對象中沒有FirstName字段。 (僅FullNameContactID)。如果您需要通過現場訂購,你需要選擇它:

select new { FirstName = ofg.FirstName, FullName = ofg.FirstName + ofg.Surname, ContactID = ofg.ContactID } 

您也可能會發現在這個邏輯,你的FullName字段沒有名稱之間加空格。如果你想要的話,你需要把它包含在邏輯中。

作爲一個附註,像FullName這樣的字段通常是實際模型而不是匿名對象的好例子。考慮這樣的事情:

public class SomeModel 
{ 
    public string FirstName { get; set; } 
    public string Surname { get; set; } 
    public int ContactID { get; set; } 

    public string FullName 
    { 
     get 
     { 
      return string.Format("{0} {1}", FirstName, Surname); 
     } 
    } 
} 

這將封裝它所屬的對象上的FullName邏輯,你可以只選擇對象的一個​​實例:

select new SomeModel { FirstName = ofg.FirstName, Surname = ofg.Surname, ContactID = ofg.ContactID } 

這樣耗時的代碼將無法必須複製創建模型的邏輯,模型本身包含它擁有的邏輯。然後,您可以繼續添加更多功能,集中到一個模型。

+1

'模型本身包含它擁有的邏輯'+1:然後你也可以很容易地適應這個邏輯。如果需要更改'String.Format'字符串以打印「LastName FirstName」而不是「FirstName LastName」... – ChrFin 2014-12-01 15:36:44

+0

謝謝,我嘗試將全名方法添加到模型中,如上所示,並得到錯誤 - 指定的類型成員'FullName'在LINQ to Entities中不受支持。僅支持初始化程序,實體成員和實體導航屬性。 – stephenjgray 2014-12-01 15:48:02

+0

@stephenjgray:你究竟做了什麼? – David 2014-12-01 15:51:36

0

試着在匿名對象的屬性添加名稱,smaple:

public ActionResult GetContactList (int? id) { 

    var contacts = from ofg in db.Contacts 
        where ((ofg.ContactId == id) && (ofg.Deleted == false)) 
        order by ofg.FirstName 
        select new { FullName = (ofg.FirstName + ofg.Surname), 
           ContactID = ofg.ContactID }; 

    return this.Direct(contacts.ToArray()); 

} 
+0

感謝Felipe,完美的工作 – stephenjgray 2014-12-01 15:51:11