开发者

Combine Linq to EF

开发者 https://www.devze.com 2023-02-18 03:55 出处:网络
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

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();
            }

       开发者_StackOverflow社区     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?


If you get no result back from a left join, then you know there are no products for that brand.

Try,

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消