简体   繁体   English

在NHibernate查询中根据不同的表设置值

[英]Setting value based on different table in NHibernate query

I am using NHibernate, and have problems with this query... I have a class Item which I want to fetch using its Id. 我正在使用NHibernate,并且对此查询有问题...我有一个类项目,我想使用其Id获取。 All fine. 一切都很好。 However, I also want a bool property on the Item class to be set to true if some other condition is set. 但是,如果设置了其他条件,我还希望将Item类中的bool属性设置为true。 Specifically this property is named IsMarked, telling if the Item is marked/stared/flagged for the user that requested it, and this information is set on a table giving the relation between Item and User. 具体来说,此属性名为IsMarked,告知是否为请求它的用户标记/标记/标记了项目,并且此信息在表格上设置,给出了项目和用户之间的关系。

Currently I'm fetching the Item, and then finding the reference - updating the property to true if the reference could be found. 目前我正在获取Item,然后查找引用 - 如果可以找到引用,则将属性更新为true。 Can I do this in one query instead? 我可以在一个查询中执行此操作吗?

var item = Session.Get<Item>(itemId);

var flaggedResult = Session.CreateCriteria<ItemWithUserFlag>()
    .Add(Restrictions.Eq("User.Id", userId))
    .Add(Restrictions.Eq("Item", item))
    .List<ItemWithUserFlag>();

if (flaggedResult.Count > 0)
    item.IsMarked = true; 

return item; 

How about using formula along with filter in your property mapping: 如何在属性映射中使用formulafilter

<property name="IsMarked" formula="(select count(*) from ItemWithUserFlag where ItemWithUserFlag.ItemId = ItemId and ItemWithUserFlag.UserId = :UserFilter.userId)" />

And filter def: 并过滤def:

<filter-def name="UserFilter">
    <filter-param name="userId" type="Int32"/>
</filter-def>

That will result in something like 这会产生类似的结果

SELECT Item.*, (select count(*) from ItemWithUserFlag where ItemWithUserFlag.ItemId = Item.ItemId and ItemWithUserFlag.UserId = ?) AS IsMarked FROM Item

As long as IsMarked is defined as bool , if count(*) returns 0 it will be converted to false and if anything > 0 it will be converted to true . 只要IsMarked被定义为bool ,如果count(*)返回0 ,它将被转换为false ,如果任何> 0 ,它将被转换为true

EDIT: Fluent representation 编辑:流利的代表

public class ItemMap : ClassMap<Item>
{
    public ItemMap()
    {
        /// ... whatever
        Map(x => x.IsMarked).Formula("(select count(*) from ItemWithUserFlag where ItemWithUserFlag.ItemId = ItemId and ItemWithUserFlag.UserId = :UserFilter.userId)");
    }
}

public class UserFilter : FilterDefinition
{
    public UserFilter()
    {
        WithName("UserFilter")
            .AddParameter("userId", NHibernate.NHibernateUtil.Int32);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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