在這種情況下創建一個新的匿名對象可能會看起來更像是這樣的:
select new { FullName = ofg.FirstName + ofg.Surname, ContactID = ofg.ContactID }
注然後這是行不通的:
OrderBy(ofg => ofg.FirstName)
因爲對象中沒有FirstName
字段。 (僅FullName
和ContactID
)。如果您需要通過現場訂購,你需要選擇它:
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 }
這樣耗時的代碼將無法必須複製創建模型的邏輯,模型本身包含它擁有的邏輯。然後,您可以繼續添加更多功能,集中到一個模型。
你的例子工作嗎?如果不是什麼例外,你會得到什麼?爲什麼在數據庫中這樣做,而不是通過代碼? – ChrFin 2014-12-01 15:27:40