Fluent NHibernate and filtering one-to-many relationship on query requiring multiple joins?

被刻印的时光 ゝ 提交于 2019-12-04 12:23:26

Heres what I've found myself in case anyone else is looking for this information.

1.Create a custom filter:

public class ItemDataFilter : FilterDefinition
{
    public ItemDataFilter()
    {
        WithName("ItemDataFilter").WithCondition("Data.DataStoreId == :DataStoreId").AddParameter("DataStoreId", NHibernate.NHibernateUtil.Int32);
    }
}

2.Modify your Fluent NHibernate property mapping (with .ApplyFilter<>()):

HasMany(x => x.Data)
    .KeyColumn("ItemId")
    .ApplyFilter<ItemDataFilter>()
    .Cascade.AllDeleteOrphan();

3.In your repository enable the filter and set it's property for the current session:

public IList<Item> GetItemsByDataStore(int DataStoreId)
    {
    using (var session = NHibernateHelper.OpenSession())
    {
        session.EnableFilter("ItemDataFilter").SetParameter("DataStoreId", DataStoreId);
        return session.CreateCriteria(typeof(Item)).List<Item>();
    }
}

Another way to do this would be to fetch all ItemData for each Item and add another non-mapped property that does this filtering.

Baz1nga

You can do this using HQL using a simple query too.. Your HQL query syntax is as follows:

 Session.CreateQuery(hqlQuery).List();

your hqlQuery will be something like this:

 var hqlQuery= string.Format("select i from Items as i inner join i.ItemData left join Users u left join DataStire ds where u.UserId=i.UserId and ds.DataStoreId=i.DataStoreId and (ds.IsGlobal=1 or ds.UserId='{0}')",userId);

 Session.CreateQuery(hqlQuery).List<Item>();

Hope this works..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!