我正在尝试编写查询以从数据库中选择数据。我有以下代码:
from notes in ctx.Notes
.Where(x => x.UserId== user.UserId
|| x.UserId == user.FamilyId
|| x.UserId == user.CompanyId).DefaultIfEmpty()
此问题是,FamilyId和CompanyId都是可为空的类型,并且可能根本没有任何值,这会破坏整个查询。我该如何重写它,使其仅在有值的情况下查找FamilyId / CompanyId?
答案 0 :(得分:4)
创建条件查询:
var users = ctx.Notes.Where(x => x.UserId == user.UserId);
if (user.FamilyId != null)
{
users = users.Union(ctx.Notes.Where(x => x.UserId == user.FamilyId));
}
if (user.CompanyId != null)
{
users = users.Union(ctx.Notes.Where(x => x.UserId == user.CompanyId ));
}
var result = users.ToArray();
答案 1 :(得分:0)
简单,只需添加一个AND子句以检查其是否不为空:
from notes in ctx.Notes.Where(x => x.UserId== user.UserId || (user.FamilyId ! =null && x.UserId == user.FamilyId) || (user.CompanyId !=null && x.UserId == user.CompanyId)).DefaultIfEmpty()