一千萬個為什麽

搜索

將linq中的屬性處理為sql

It's my first LINQ TO SQL Project , So definitely my question could be naive .

到目前為止,我曾經在每個DateTime屬性旁邊的Business Object中創建新屬性,這是因為我需要在我的DateTime屬性中進行一些處理,並以特殊的字符串格式顯示它以綁定到UI控件。喜歡:


private DateTime _insertDate;
/// 
/// I have "InertDate" field in my Table on Database
/// 
public DateTime InsertDate
{
    get { return _insertDate; }
    set { _insertDate = value; }
}


// Because i need to do some processing I create a readonly string property that pass InsertDate to Utility method and return special string Date public string PInsertDate { get { return Utility.ToSpecialDate(_insertDate); } }

我的問題是我不知道如何在LINQ中做到這一點。我確實喜歡跟隨,但我得到運行時錯誤。 “方法'System.String ToSpecialDate(System.Object)'沒有支持的SQL轉換”


ToosDataContext db = new ToosDataContext();
var newslist = from p in db.News
               select new {p.NewsId,p.Title,tarikh =MD.Utility.ToSpecialDate( p.ReleaseDate)};


GridView1.DataSource = newslist; GridView1.DataBind();

最佳答案

您需要將數據庫中執行的查詢與正在進行的處理分開。嘗試這個:

var newslist = db.News
                //First do a select in SQL
                 .Select(p => new {p.NewsId, p.Title, p.ReleaseDate})
                 .AsEnumerable()//Do the rest in process
                 .Select(p => new {p.NewsId, p.Title, 
                         tarikh = MD.Utility.ToSpecialDate(p.ReleaseDate) });

轉載註明原文: 將linq中的屬性處理為sql