2008-10-14 59 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); 

这是否把戏对我来说。