2014-01-26 31 views
1

我有一個下拉列表,我想用數據庫中的五個字段填充下拉列表。我使用的是Entity framework 6lambda/linq。 我有兩個問題。在lambda/linq中添加可以conatin爲空的字段

  1. 當我一起添加字段時,它只顯示下拉列表中的第一個字段(a.tblRegion.Name)。我希望它看起來像「地區」「商店」「位置」「日期」。除了「區域」字段外,它們都可以爲空。
  2. 我也希望其中一個字段是日期字段,但會引發錯誤。

我現在的代碼看起來像這樣。

var query = db.tblActivityReports.Where(ap => ap.Deleted == false) 
    .Select(a => new 
    { 
    activity = a.tblRegion.Name != "" ? a.tblRegion.Name : string.Empty + " " + 
    a.tblStore.Name != "" ? a.tblStore.Name : string.Empty + " " + 
    a.Location != "" ? a.Location : string.Empty, 
    activityId = a.ActivityReportId, 
    participant = a.tblActivityParticipants 
    }); 

如果我添加日期字段我得到這個錯誤: "Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."

提前感謝!

+0

以下哪個領域之一是第一?哪一個是約會? –

+0

啊,對不起。我一直在來回改變它。日期字段丟失了。 – Fred

+0

嗯,評論部分不是我的朋友。 :)你的意思是什麼? – Fred

回答

1

我建議你從數據庫中獲取所需的數據,然後在客戶端進行數據格式化 - 實際爲數據庫上的UI格式化字符串不是一個好主意。因此,加載所有需要的數據後,你將能夠使用的String.Format和日期時間轉換爲字符串:

db.tblActivityReports 
    .Where(ar => !ar.Deleted) 
    .Select(ar => new { 
    RegionName = ar.tblRegion.Name, 
    StoreName = (ar.tblStore == null ? null : ar.tblStore.Name), 
    ar.Location, 
    ar.ActivityDate, 
    ActivityId = ar.ActivityReportId, 
    Participants = ar.tblActivityParticipants 
    }) 
    .AsEnumerable() // move query to memory 
    .Select(x => new { 
    Activity = String.Format("{0}{1}{2}{3}", 
        x.RegionName, x.StoreName, x.Location, x.ActivityDate), 
    x.ActivityId, 
    x.Participants 
    }); 

你甚至可以映射結果一些視圖模型將負責返回格式化字符串。

提示:如果您想以空格連接值,那麼你可以使用的string.join而不是格式:

Activity = String.Join(" ", 
(new object[] { x.RegionName, x.StoreName, x.Location, x.ActivityDate }) 
.Where(o => o != null)) 
+0

非常感謝!這幫了我很多! – Fred

+0

我不知道它是不是一個vb.net的東西,但在C#中至少這個ar.tblStore = null? null ...應該是ar.tblStore == null?空值。 – Fred

+0

@Fred你是對的,那只是錯字 –

相關問題