我想在删除品牌之前检查品牌中是否存在任何产品。我将以下Linq写入实体框架代码
int count =0;
if(!_entitiesContext.Product.Any(p=>p.BrandID==brandID))
{
var brand =
(from c in _entitiesContext.Brand
where c.BrandID == brandID
select c).FirstOrDefault();
_entitiesContext.DeleteObject(brand);
count = _entitiesContext.SaveChanges();
}
return count>0;
上面的代码将访问数据库两次,如何将两者结合起来,以便生成一个使用EXISTS关键字的SQL查询?
答案 0 :(得分:0)
如果您从左连接中得不到任何结果,那么您就知道该品牌没有产品。
尝试,
var query1 = from b in _entitiesContext.Brand
join p in _entitiesContext.Product on
on b.BrandID equals p.BrandID
into bpGroup
where b.BrandID == brandID
select new
{
Brand = b
, Count = bpGroup.Count()
};
if (Count == 0 )
{
// delete Brand
}