NHibernate中“不在”或“不存在”的标准

时间:2013-11-05 18:24:49

标签: c# .net database nhibernate

我正在尝试在NHibernate中为以下语句创建条件:

SELECT *
  FROM InventoryItems
  where id not in (select inventory_id from InventoryItemCategories where Category_Id = 'EB0DA6DE-DC18-4306-9EF7-E506463555A9')

或者我认为这个更好

SELECT *
  FROM InventoryItems
  where id not exists (select inventory_id from InventoryItemCategories where Category_Id = 'EB0DA6DE-DC18-4306-9EF7-E506463555A9')

我试过这个,但它不起作用:

 var criteria = Session.CreateCriteria<InventoryItem>()
      .Add(Subqueries.WhereNotExists(("id"), DetachedCriteria.For<InventoryItemCategories>()
       .Add(Restrictions.Eq("Category_id",inventoryCategoryId))));

非常感谢您的帮助

4 个答案:

答案 0 :(得分:1)

如果您将两个实体联系起来,那将更容易

public class InventoryItem
{
    public virtual object Id{get;set;}
    public virtual IList<InventoryItemCategory> InventoryItemCategories{get;set;}
}
public class InventoryItemCategoriy
{
    public virtual InventoryItem InventoryItem{get;set;}
}
public class InventoryItemMap : ClassMap<InventoryItem>
{
    public InventoryItem()
    {
        Id(x=>x.Id);
        HasMany(x=>x.InventoryItemCategories).KeyColumn("Inventory_id");
    }
}
public class InventoryItemCategoryMap:ClassMap<InventoryItemCategory>
{
    public InventoryItemCategory()
    {
        References(x=>x.InventoryItem).Column("Id");
    }
}

您的查询如下

session.Query<InventoryItem>().Where(x=>!x.InventoryItemCategories.Any(c=>c.Id=="EB0DA6DE-DC18-4306-9EF7-E506463555A9")).ToList();

答案 1 :(得分:0)

您可以使用子查询或非限制,例如:

var subqueryFoodsWithCancerogenousSubstances = 
    DetachedCriteria.For(typeof(FoodCancerSubst))
            .SetProjection(Projections.Property("FoodId"));

ICriteria noCancerFood =
    session.CreateCriteria(typeof(Food))
    .Add(Subqueries.NotIn(subqueryFoodsWithCancerogenousSubstances))
    // check ID, else use PropertyNotIn(...)

或将IN子句用于没有NotIn的

的析取值列表
    .Add(Restrictions.Not(Restrictions.In("Id", cancerogenousFoodIdsList)))

答案 2 :(得分:0)

你不能这样做:

criteria.Add(Restrictions.Not(Restrictions.In ("id", detachedCrit));

答案 3 :(得分:-1)

IN通常会映射到Contains来电,您可以在其中反转参数:

var subquery = context.InventoryItemCategories
    .Where(category => category.Category_Id == 
        'EB0DA6DE-DC18-4306-9EF7-E506463555A9')
    .Select(category => category.inventory_id);

var query = context.InventoryItems.Where(item => !subquery.Contains(item.id));