2008-10-14 70 views
4

我剛問過this question。這導致我一個新的問題:)Linq to SQL:.FirstOrDefault()不適用於選擇新{...}

直到這一點,我已經使用了以下模式選擇LINQ to SQL的東西,目的是能夠處理0查詢返回的「行」:

var person = (from p in [DataContextObject].Persons 
       where p.PersonsID == 1 
       select new p).FirstOrDefault(); 

if (person == null) 
{ 
    // handle 0 "rows" returned. 
} 

但我不能用FirstOrDefault()當我這樣做:

var person = from p in [DataContextObject].Persons 
      where p.PersonsID == 1 
      select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }; 

// Under the hood, this pattern generates a query which selects specific 
// columns which will be faster than selecting all columns as the above 
// snippet of code does. This results in a performance-boost on large tables. 

如何檢查查詢返回0「行」,使用第二圖案?



UPDATE:

我想是因爲我想指定查詢變量(this._user)的結果,我的生成失敗宣佈與[DataContext].User類型。

this._user = (from u in [DataContextObject].Users 
       where u.UsersID == [Int32] 
       select new { u.UsersID }).FirstOrDefault(); 

編譯錯誤:無法隱式轉換類型 「AnonymousType#1」 至 「[DataContext的]。用戶」。

有關如何解決此問題的任何想法?我需要製作自己的對象嗎?

回答

1

關於您的更新:您必須創建您自己的類型,將this._user更改爲int,或者選擇整個對象,而不僅僅是特定的列。

1
if (person.Any()) /* ... */; 

OR

if (person.Count() == 0) /* ... */; 
0

你仍然可以使用FirstOrDefault。只要有

var PersonFields = (...).FirstOrDefault() 

PersonFields將爲null或具有您創建的屬性的對象。

13

爲什麼你會繼續做同樣的事情?它給你一個錯誤?

var person = (from p in [DataContextObject].Persons 
       where p.PersonsID == 1 
       select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }).FirstOrDefault(); 

if (person == null) {  
    // handle 0 "rows" returned. 
} 

它仍然是就像你實際對象的引用對象,所以你不知道實際類型的代碼被編譯之前,它僅僅是匿名的。

+0

同意,上述應該工作,除非有一個不相關的運行時錯誤。 – Codewerks 2008-10-14 16:25:58

2

更新:

I see now what you were actually asking! Sorry, my answer no longer applies. I thought you were not getting a null value when it was empty. The accepted response is correct, if you want to use the object out of scope, you need to create a new type and just use New MyType(...). I know DevEx's RefactorPro has a refactoring for this, and I think resharper does as well.

呼叫.FirstOrDefault(空)是這樣的:

string[] names = { "jim", "jane", "joe", "john", "jeremy", "jebus" }; 
var person = (
    from p in names where p.StartsWith("notpresent") select 
     new { Name=p, FirstLetter=p.Substring(0,1) } 
    ) 
    .DefaultIfEmpty(null) 
    .FirstOrDefault(); 

MessageBox.Show(person==null?"person was null":person.Name + "/" + person.FirstLetter); 

這是否把戲對我來說。