2012-04-01 75 views
0

比較我有以下型號:與內子查詢計數(NHibernate的QueryOver API)

create table Products (
    Id UNIQUEIDENTIFIER not null, 
    Name NVARCHAR(255) null, 
    CategoryId UNIQUEIDENTIFIER not null, 
    primary key (Id), 
    unique (Name, CategoryId) 
) 

create table Rates (
    Id UNIQUEIDENTIFIER not null, 
    Price NUMERIC(19,5) not null, 
    TimeStamp DATETIME not null, 
    UserId UNIQUEIDENTIFIER not null, 
    ProductId UNIQUEIDENTIFIER not null, 
    primary key (Id), 
    unique (Price, UserId, ProductId) 
) 

create table Categories (
    Id UNIQUEIDENTIFIER not null, 
    Name NVARCHAR(255) not null unique, 
    primary key (Id) 
) 

編輯:領域模型如下:

public class Category 
{ 
    public string Name { get; set; } 
    public IList<Product> Products { get; set; } 
    public Guid Id { get; set; } 
} 

public class Product 
{ 
    public string Name { get; set; } 
    public Category Category { get; set; } 
    public IList<Rate> Rates { get; set; } 
    public Guid Id { get; set; } 
} 

public class Rate 
{ 
    public User User { get; set; } 
    public Product Product { get; set; } 
    public decimal Price { get; set; } 
    public DateTime TimeStamp { get; set; } 
    public Guid Id { get; set; } 
} 

我想要做什麼是選擇所有沒有關聯產品和相關費率的類別。即在SQL中,這看起來像:

select * from Categories category where 
    (select count(*) 
    from Products product 
    inner join Rates rate on rate.ProductId = product.Id 
    where product.CategoryId = category.Id) = 0; 

如何使用QueryOver API執行此操作?

+0

我沒有看到任何域模型;我只看到你的數據庫模型。爲了能夠回答你的問題,我們必須知道類的樣子。 (接下來,我認爲你的SQL查詢是錯誤的)。 – 2012-04-01 19:04:04

+0

@FrederikGheysels,編輯。 – eigenein 2012-04-01 19:37:15

回答

0

該解決方案發現:

Category categoryAlias = null; 
session.QueryOver<Category>(() => categoryAlias) 
    .WithSubquery 
    .WhereNotExists(QueryOver.Of<Product>() 
     .Where(product => product.Category.Id == categoryAlias.Id) 
     .JoinQueryOver<Rate>(product => product.Rates) 
     .Select(product => product.Category)) 
    .List<Category>(); 

感謝https://stackoverflow.com/a/5196609/359730

0

我無法檢查生成的sql,但你可以試試這個,也許是幫助:

Product product = null; 
Rate rate = null; 

_session.QueryOver<Category>() 
    .JoinAlias(category => category.Products,() => product) 
    .JoinAlias(() => product.Rate,() => rate) 
    .Where(Restrictions.Eq(Projections.Count(() => product.Id), 0) 
    .List<Category>();