将 Linq 合并到 EF
我想在删除品牌之前检查该品牌是否存在任何产品。我编写了以下 Linq to 实体框架代码
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 查询?
I want to check if there is any product exist in a brand before deleting the brand. I write the following Linq to entity framework code
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;
The above code will access the database twice, how can I combine the two so that one sql query using EXISTS keyword is generated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您从左连接中没有得到任何结果,那么您就知道该品牌没有产品。
尝试,
If you get no result back from a left join, then you know there are no products for that brand.
Try,