Linq to entities 将Linq合并到EF

Linq to entities 将Linq合并到EF,linq-to-entities,Linq To Entities,在删除某个品牌之前,我想检查该品牌中是否存在任何产品。我编写以下Linq到实体框架代码 int count =0; if(!_entitiesContext.Product.Any(p=>p.BrandID==brandID)) { var brand = (from c in _entitiesContext.Brand

在删除某个品牌之前,我想检查该品牌中是否存在任何产品。我编写以下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查询?

如果您从左连接中没有得到结果,那么您就知道该品牌没有产品

试试看


如果您从左连接中没有得到任何结果,那么您知道该品牌没有产品

试试看

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
}