简体   繁体   中英

NHibernate queryover join many to many

I am really banging my head with this NHibernate query :) to write a join. I have many to many relation with Asset and Product. Please find below the table model

public class Asset
{
    string Id { get; set; }
    List<Product> Products { get; set; }
}

public class Product
{
    string Id { get; set; }
    List<Asset> Assets { get; set; }
}

Here is the code i am trying with QueryOver

Product productAlias = null;
Asset assetAlias = null;
var query = Session.QueryOver<Asset>(()=>assetAlias);

if (!string.IsNullOrEmpty(title))
    query.WhereRestrictionOn(x => x.Title).IsLike(title, MatchMode.Anywhere);

if (!string.IsNullOrEmpty(productNumber))
{
    query.WhereRestrictionOn(asset => asset.Products.First().Id).Equals(productNumber);
}

    var result = query.List<Asset>();

Can anyone help how to write the join queryover so that i want to find all the asset whose title is like title and the productnumber is equal to productnumber?

I am not getting the result with the above code.

The sql query i am trying to achieve is :

select a.* from Asset a ,
ManyToManyTable b on a.mat_id=b.mat_id
where a.title like '%test%' and b.prod_no='212300733'

Thanks

You need to use .JoinQueryOver() to change the context of what you're placing the WHERE restrictions on. Learn more at http://blog.andrewawhitaker.com/blog/2014/03/16/queryover-series-part-2-basics/ . This should be close to what you are looking for. You state that you're looking for a left join, but since the join here is only applied when there is a product number specified, there should be no problems with that. It's possible to apply .Left.JoinQueryOver() if you find you need it though.

var query = Session.QueryOver<Asset>();

if (!string.IsNullOrEmpty(title))
    query = query.WhereRestrictionOn(x => x.Title).IsLike(title, MatchMode.Anywhere);

if (!string.IsNullOrEmpty(productNumber))
{
    query = query.JoinQueryOver(a => a.Products).Where(p => p.Id == productNumber);
}

var result = query.List<Asset>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM