2013-03-27 21 views
0

我有這個疑問:C# - LINQ到實體查詢屬性的價值附加到一個變量

var sole = SoleService.All().Where(c => c.Status != 250) 
       .Select(x => new { 
        ID = x.ID, Code = new {CodeName = x.Code + x.Country}, 
        Name = x.Name 
       }) 
       .Distinct() 
       .OrderBy(s => s.Code); 

喜歡這個?給我一個錯誤。我想要結合CodeCountry像concat字符串,所以我可以使用新的變量爲我的數據源。喜歡的東西 - 001France

P.S

我使用的是什麼,並且正在現在的問題是這樣的:

var sole = SoleService.All().Where(c => c.Status != 250) 
       .Select(x => new { 
        ID = x.ID, Code = x.Code, Name = x.Name, Country = x.Country }) 
       .Distinct() 
       .OrderBy(s => s.Code); 

所以我需要的是修改此查詢,以便我可以使用Code +Country作爲一個變量。以上只是我的嘗試,我認爲會起作用。

+3

你有什麼錯誤? – 2013-03-27 10:34:00

+1

您能否提供您正在獲得的異常,以及SoleService.All()返回的更多上下文? – 2013-03-27 10:35:01

+1

SoleService是一個Enumerable嗎? – 2013-03-27 10:36:03

回答

5

聽起來像:

var sole = SoleService.All().Where(c => c.Status != 250) 
       .AsEnumerable() 
       .Select(x => new { 
           ID = x.ID, 
           Code = x.Code + x.Country, 
           Name = x.Name 
           }) 
       .Distinct() 
       .OrderBy(s => s.Code); 

你不需要內部匿名類型的。如果您正在使用EF,則不支持正弦字符串+,請在選擇之前調用AsEnumerable

+0

'DbArithmeticExpression參數必須有一個數字通用類型.'當這樣做時。 – Leron 2013-03-27 10:46:44

+0

你的'Code'類型是什麼? – 2013-03-27 10:47:58

+0

該類型是'nvarchar'。我認爲'ToString()'在LINQ2Entities中不可用 – Leron 2013-03-27 10:52:01

2

您無法按s.Code排序,因爲它是匿名類型的實例。我會跟

var sole = SoleService.All().Where(c => c.Status != 250) 
     .Select(x => new { ID = x.ID, Code = new {CodeName = x.Code + x.Country}, Name = x.Name }) 
     .Distinct() 
     .OrderBy(s => s.Code.CodeName); 
+0

DbArithmeticExpression參數必須有一個數字通用類型。顯然'+'不是一個類。 – Leron 2013-03-27 10:50:28

0

嘗試去加的ToString(),因爲這個問題應該是+運營商相信你嘗試添加數值屬性...

就像是:

var sole = SoleService.All().Where(c => c.Status != 250) 
     .Select(x => new { ID = x.ID, Code = new {CodeName = x.Code.ToString() + x.Country.ToString()}, Name = x.Name }) 
     .Distinct() 
     .OrderBy(s => s.Code); 
+0

'LINQ to Entities does not recognized the method'System.String ToString()'method,and this method can not be transolve into a store expression.' - error – Leron 2013-03-27 10:48:59

+0

您可以嘗試Convert.ToString(x.Code) – Pouki 2013-03-27 10:53:39

+0

不是它是同樣的錯誤。 – Leron 2013-03-27 10:57:33