首先,我做了一些搜索這個問題的答案...但我找不到任何東西,因爲我不知道我用什麼功能被稱爲。LINQ:爲什麼我不能在返回的對象中聲明新對象?
以下代碼中的DBEntities由devart爲Oracle數據庫連接生成。
爲什麼第一個例子工作,第二個例子只給我一個System.NullReferenceException?
有效代碼:
using (DBEntities context = new DBEntities())
{
var infos = (from info in context.Infos
where info.Index == index
orderby info.Name
select new
{
Name = info.Name,
MRN = info.MRN,
UnitNumber = (info.UnitNum == null) ? -1 : (decimal)info.UnitNum,
UnitName = (info.UnitName == null) ? String.Empty : info.UnitName
}).Distinct();
foreach (var info in infos)
{
// *do stuff*
}
}
代碼,讓異常(一旦達到的foreach例外僅見於):
using (DBEntities context = new DBEntities())
{
var infos = (from info in context.Infos
where info.Index == index
orderby info.Name
select new Member()
{
Name = info.Name,
MRN = info.MRN,
CurrentUnit = new Unit()
{
UnitNumber = (info.UnitNum == null) ? -1 : (decimal)info.UnitNum,
UnitName = (info.UnitName == null) ? String.Empty : info.UnitName
}
}).Distinct();
foreach (Member info in infos)
{
// *do stuff*
}
}
編輯: 我想補充一點,也可以使用:
using (DBEntities context = new DBEntities())
{
var infos = (from info in context.Infos
where info.Index == index
orderby info.Name
select new Member()
{
Name = info.Name,
MRN = info.MRN
}).Distinct();
foreach (Member info in infos) //Exception is thrown here.
{
// *do stuff*
}
}
你有什麼異常? – Thebigcheeze 2012-04-06 22:20:07
@Thebigcheeze System.NullReferenceException – bsara 2012-04-06 22:23:10
是否確定你的集合包含數據? – Tigran 2012-04-06 22:25:09