我有一个LINQ查询,可以在我的DAL中使用EF工作正常:
using (var mLEntities = new myLab02Entities1())
{
var test = from c in mLEntities.Chemicals
from u in c.Usages
select new
{
cChemID = c.Chem_ID,
c.Name,
c.Supplier,
c.Grade,
c.OrderNo,
c.BatchNo,
c.EntryDate,
c.CreatedBy,
cUser = u.Person.PersName,
uChemID = u.Chem_ID,
u.Study_ID,
u.UsedBy,
uUser = u.Person.PersName,
u.UseDate,
u.Project.StudyNo,
u.Project.ProjectName,
};
Usages是Chemicals的导航属性(1 chem:n usa),Person和Projects都是Usages的导航属性(均为1:1)。 然后我想把这个查询放在我的业务逻辑中并写道:
IList<ChemicalBDO> chemicalListBDO = chemListDAO.GetChemicalsListFromDB();
var test = from c in chemicalListBDO
from u in c.Usages
select new
{
cChemID = c.Chem_ID,
c.Name,
c.Supplier,
c.Grade,
c.OrderNo,
c.BatchNo,
c.EntryDate,
c.CreatedBy,
cUser = u.Person.PersName,
uChemID = u.Chem_ID,
u.Study_ID,
u.UsedBy,
uUser = u.Person.PersName,
u.UseDate,
u.Project.StudyNo,
u.Project.ProjectName
};
也就是说,我首先查询我的EF DBcontext并获取我的化学实体,然后我写了一个针对这个化学实体的查询。 对我来说奇怪的是,最后一个代码抛出一个System.NullReferenceExeption,因为u.Person和u.Project可以为NULL。但是第一个查询不会抛出异常,原因是什么? 如何处理select查询中的NULL引用,我可以用“if”,“?”检查NULL要么 ”??” ?
Btw:我认为在DAL中进行复杂的查询并不是一个好的编程习惯,是真的还是我可以让代码存在? 任何帮助表示赞赏。答案 0 :(得分:0)
这应解决这个问题:
IList<ChemicalBDO> chemicalListBDO = chemListDAO.GetChemicalsListFromDB();
var test = from c in chemicalListBDO
from u in c.Usages
select new
{
cChemID = c.Chem_ID,
c.Name,
c.Supplier,
c.Grade,
c.OrderNo,
c.BatchNo,
c.EntryDate,
c.CreatedBy,
cUser = u.Person != null ? u.Person.PersName : string.Empty,
uChemID = u.Chem_ID,
u.Study_ID,
u.UsedBy,
uUser = u.Person != null ? u.Person.PersName : string.Empty,
u.UseDate,
u.Project != null ? u.Project.StudyNo : -1,
u.Project != null ? u.Project.ProjectName : string.Empty
};