首先,我做了一些寻找这个问题的答案......但我找不到任何东西,因为我不知道我正在使用的功能是什么。
以下代码中的 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*
}
}