简体   繁体   中英

NHibernate QueryOver complex query

I currently working on ac#, MVC3, NHibernate (on MSSQL 2008) application. I'll provide a simplified example as I think that's the best way to understand this.

Models:

class Stock
{
    public Company Company {get;set;} 
    public Product Product {get;set;} 
    public int quantity {get;set;}  
}   
class TransactionHeader
{
    public Company FromCompany {get;set;}
    public Company ToCompany {get;set;}
    public IList<TransactionRow> Rows {get;set;}
}
class TransactionRows
{
    public Product Product {get;set;}
    public TransactionHeader Header {get;set;}
    public int Quantity {get;set;}
}
class Company
{
    public Country Country {get;set;}
    public State State {get;set;}
    public string Name {get;set;}
}

My ultimate goal is to produce a list containing:

product name, company name, country name, state name, current stock qty, incomming stock qty, outgoing stock qty

I can do this for current stock with this query:

var stockQuery = session.QueryOver<Stock>(() => s)
    .JoinAlias<Company>(() => s.company, () => c, NHibernate.SqlCommand.JoinType.InnerJoin, null)
    .JoinAlias<State>(() => c.State, () => state, NHibernate.SqlCommand.JoinType.InnerJoin, null)
    .JoinAlias<Country>(() => c.Country, () => country, NHibernate.SqlCommand.JoinType.InnerJoin, null)
    .JoinAlias<Product>(() => s.product, () => p, NHibernate.SqlCommand.JoinType.InnerJoin, null);
if (productId.HasValue) { stockQuery = stockQuery.Where(() => p.Id == productId); }
var stock = stockQuery.SelectList(list => list
            .Select(() => s.currentStock).WithAlias(() => rowVM.CurrentStock)
            .Select(() => c.Description).WithAlias(() => rowVM.CompanyName)
            .Select(() => state.Description).WithAlias(() => rowVM.StateName)
            .Select(() => country.Description).WithAlias(() => rowVM.CountryName)
            .Select(() => p.Description).WithAlias(() => rowVM.ProductName))
        .TransformUsing(Transformers.AliasToBean<StockLevelRowVM>())
        .List<StockLevelRowVM>();

What I'm stuck on is how to add in the incomming and outgoing stock based on the TransactionHeader / TransactionRow data. Here is my attempt at a query to get incomming stock numbers:

            var incommingQuery = session.QueryOver<TransactionRow>(() => itr)
                .JoinAlias<TransactionHeader>(() => itr.TransactionHeader, () => ith, NHibernate.SqlCommand.JoinType.InnerJoin, null)
                .JoinAlias<Company>(() => ith.ToCompany, () => c, NHibernate.SqlCommand.JoinType.InnerJoin, null)
                .JoinAlias<Product>(() => itr.Product, () => p, NHibernate.SqlCommand.JoinType.InnerJoin, null)
                .SelectList(list => list
                    .SelectGroup(() => new { ith.ToCompany, itr.Product })
                    .Select(() => itr.Quantity).WithAlias(() => detail.Quantity)
                    .Select(() => p.Id).WithAlias(() => detail.ProductId)
                    .Select(() => c.Id).WithAlias(() => detail.CompanyId))

The group by multiple properties does not seem to work:

 Could not determine member from new <>f__AnonymousType3`2(ToCompany = value(<Stuff>).ith.ToCompany, Product = value(<Stuff>).itr.Product)

So this leads me to 2 questions:

  1. Am I going about this whole thing wrong? Would a stored proc be a better solution?
  2. If this approach is fine then how can I group by multiple fields?

EDIT: Example of the sort of SQL I'm wanting to generate:

SELECT c.Description CompanyName, 
    p.Description ProductName,
    cc.Description CountryName, 
    cs.Description StateName,
    tmp.CurrentStock, 
    tmp.OutgoingStock, 
    tmp.IncommingStock
FROM
(
    SELECT results.CompanyId, 
        results.ProductId, 
        SUM(results.CurrentStock) CurrentStock, 
        SUM(results.IncommingStock) IncommingStock, 
        SUM(results.OutgoingStock) OutgoingStock
    FROM (
        SELECT 
            c.Id CompanyId,
            p.Id ProductId,
            s.CurrentStock, 
            0 IncommingStock,
            0 OutgoingStock
        FROM Stock s
        INNER JOIN Company c ON c.Id = s.Company
        INNER JOIN [State] cs ON cs.Id = c.[State]
        INNER JOIN Country cc ON cc.Id = cs.Country
        INNER JOIN Product p ON p.Id = s.Product
        WHERE (@CompanyId IS NULL OR c.Id = @CompanyId) AND
            (@CountryId IS NULL OR cc.Id = @CountryId) AND
            (@StateId IS NULL OR cs.Id = @StateId) AND
            (@ProductId IS NULL OR p.Id = @ProductId)
        UNION   
        SELECT 
            c.Id CompanyId,
            p.Id ProductId,
            0 CurrentStock, 
            0 IncommingStock,
            tr.Quantity OutgoingStock
        FROM TransactionRow tr
        INNER JOIN TransactionHeader th ON th.Id = tr.TransactionHeader
        INNER JOIN Company c ON c.Id = th.FromCompany
        INNER JOIN [State] cs ON cs.Id = c.[State]
        INNER JOIN Country cc ON cc.Id = cs.Country
        INNER JOIN Product p ON p.Id = tr.Product
        WHERE (@CompanyId IS NULL OR c.Id = @CompanyId) AND
            (@CountryId IS NULL OR cc.Id = @CountryId) AND
            (@StateId IS NULL OR cs.Id = @StateId) AND
            (@ProductId IS NULL OR p.Id = @ProductId)
        UNION   
        SELECT 
            c.Id CompanyId,
            p.Id ProductId,
            0 CurrentStock, 
            tr.Quantity IncommingStock,
            0 OutgoingStock
        FROM TransactionRow tr
        INNER JOIN TransactionHeader th ON th.Id = tr.TransactionHeader
        INNER JOIN Company c ON c.Id = th.ToCompany
        INNER JOIN [State] cs ON cs.Id = c.[State]
        INNER JOIN Country cc ON cc.Id = cs.Country
        INNER JOIN Product p ON p.Id = tr.Product
        WHERE (@CompanyId IS NULL OR c.Id = @CompanyId) AND
            (@CountryId IS NULL OR cc.Id = @CountryId) AND
            (@StateId IS NULL OR cs.Id = @StateId) AND
            (@ProductId IS NULL OR p.Id = @ProductId)
    ) results
    GROUP BY results.CompanyId, results.ProductId
) tmp
INNER JOIN Company c ON c.Id = tmp.CompanyId
INNER JOIN [State] cs ON cs.Id = c.[State]
INNER JOIN Country cc ON cc.Id = cs.Country
INNER JOIN Product p ON p.Id = tmp.CompanyId

Edit 2: Second version of desired SQL

SELECT 
    c.Id CompanyId,
    c.Description CompanyName,
    p.Id ProductId,
    p.Description ProductName,
    cs.Description StateName,
    cc.Description CountryName,
    SUM(s.CurrentStock) CurrentStock, 
    SUM(ttr.Quantity) IncommingStock,
    SUM(ftr.Quantity) OutgoingStock
FROM Stock s
INNER JOIN Company c ON c.Id = s.Company
INNER JOIN [State] cs ON cs.Id = c.[State]
INNER JOIN Country cc ON cc.Id = cs.Country
INNER JOIN Product p ON p.Id = s.Product
LEFT JOIN TransactionHeader fth ON fth.FromCompany = c.Id
LEFT JOIN TransactionRow ftr ON ftr.TransactionHeader = fth.ID 
    AND ftr.Product = p.Id
LEFT JOIN TransactionHeader tth ON tth.ToCompany = c.Id
LEFT JOIN TransactionRow ttr ON ttr.TransactionHeader = tth.ID 
    AND ttr.Product = p.Id
WHERE (@CompanyId IS NULL OR c.Id = @CompanyId) AND
    (@CountryId IS NULL OR cc.Id = @CountryId) AND
    (@StateId IS NULL OR cs.Id = @StateId) AND
    (@ProductId IS NULL OR p.Id = @ProductId)   
GROUP BY p.Id, c.Id, c.Description, p.Description, 
    cs.Description, cc.Description

Thanks very much to Andrew, who prompted me to write out the SQL and thus figure this one out.

There were a few things I was missing setup wise:

  1. Company needed two extra properties:

     public virtual IList<TransactionHeader> TransactionsFromCompany { get; set; } public virtual IList<TransactionHeader> TransactionsToCompany { get; set; } 
  2. My automapping needed to be overridden to map these to the appropriate columns:

     .Override<Company>(m => { m.HasMany(c => c.TransactionsFromCompany) .KeyColumn("FromCompany"); m.HasMany(c => c.TransactionsToCompany) .KeyColumn("ToCompany"); } 
  3. Now I could write the query:

     StockLevelRowVM rowVM = null; Stock s = null; Company c = null; State state = null; Country country = null; Product p = null; TransactionHeader ith = null; TransactionRow itr = null; TransactionHeader oth = null; TransactionRow otr = null; var stockQuery = session.QueryOver<Stock>(() => s) .JoinAlias<Company>(() => s.company, () => c, NHibernate.SqlCommand.JoinType.InnerJoin, null) .JoinAlias<State>(() => c.State, () => state, NHibernate.SqlCommand.JoinType.InnerJoin, null) .JoinAlias<Country>(() => c.Country, () => country, NHibernate.SqlCommand.JoinType.InnerJoin, null) .JoinAlias<Product>(() => s.product, () => p, NHibernate.SqlCommand.JoinType.InnerJoin, null) .JoinAlias<TransactionHeader>(() => c.TransactionsFromCompany, () => oth, NHibernate.SqlCommand.JoinType.LeftOuterJoin, null) .JoinAlias<TransactionRow>(() => oth.Rows, () => otr, NHibernate.SqlCommand.JoinType.LeftOuterJoin, null) .JoinAlias<TransactionHeader>(() => c.TransactionsToCompany, () => ith, NHibernate.SqlCommand.JoinType.LeftOuterJoin, null) .JoinAlias<TransactionRow>(() => ith.Rows, () => itr, NHibernate.SqlCommand.JoinType.LeftOuterJoin, null); if (productId.HasValue) { stockQuery = stockQuery.Where(() => p.Id == productId); } if (companyId.HasValue) { stockQuery = stockQuery.Where(() => c.Id == companyId); } if (stateId.HasValue) { stockQuery = stockQuery.Where(() => state.Id == stateId); } if (countryId.HasValue) { stockQuery = stockQuery.Where(() => country.Id == countryId); } <call generic paging methods for IQueryOver> result = stockQuery.SelectList(list => list .SelectGroup(() => c.Id) .SelectGroup(() => p.Id) .SelectGroup(() => c.Description).WithAlias(() => rowVM.CompanyName) .SelectGroup(() => state.Description).WithAlias(() => rowVM.StateName) .SelectGroup(() => country.Description).WithAlias(() => rowVM.CountryName) .SelectGroup(() => p.Description).WithAlias(() => rowVM.ProductName) .SelectSum(() => s.currentStock).WithAlias(() => rowVM.CurrentStock) .SelectSum(() => otr.Quantity).WithAlias(() => rowVM.OutgoingStock) .SelectSum(() => itr.Quantity).WithAlias(() => rowVM.IncommingStock)) .TransformUsing(Transformers.AliasToBean<StockLevelRowVM>()) .List<StockLevelRowVM>().ToList(); 

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