开发者

Nhibernet select count

I have two entity

A:

public class Product
{
    pu开发者_运维技巧blic virtual int ID { get; set; }
    public virtual IList<Picture> Pictures { get;set;}
}

B:

public class Picture
{
    public virtual int ID { get;set;}
    public virtual Product { get;set;}
    public virtual Path { get;set;}
}

How do i using NHibernate ICriteria select a list containing only products with a picture count larger than 0

regards keld


If you need some exact value of pictures you can use this:

Product productAlias = null;  
var criteria = CurrentSession.CreateCriteria(typeof(Product), () => productAlias);
ICriteria productsCriteria = criteria.CreateCriteria<Product>(x => x.Pictures);

DetachedCriteria picturesCount = DetachedCriteria.For<Picture>();
picturesCount.SetProjection(Projections.RowCount());
picturesCount.Add<Picture>(x => x.Product.ID == productAlias.ID);

productsCriteria.Add(Subqueries.Gt(/*number of pictures*/, picturesCount));


return criteria.List<Customer>();

If you just need not empty collection then you can use IsNotEmpty restriction


you dint need to use a criteria query for this. You can do it using simple Linq

public IEnumerable<Product> GetProductWithPictures(IEnumerable<Product> allProducts)
{
    return allProducts.Where(x=>x.Pictures.Any());
}

Note the use of Any inside there which is faster than doing a count > 0.

Sorry I kinda forgot you are retrieving it from the dB. Here is what you need to do in that case.

public IEnumerable<Product> GetProductWithPictures()
{
    return Session.Linq<Product>.Where(x=>x.Pictures.Any());
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜