我刚问过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的]。用户”。
有关如何解决此问题的任何想法?我需要制作自己的对象吗?
同意,上述应该工作,除非有一个不相关的运行时错误。 – Codewerks 2008-10-14 16:25:58