Как объединить 5 разных типов запросов linq в один на основе столбца - PullRequest
0 голосов
/ 12 октября 2011

Я действительно запутался в отчете, который мне нужен. На сегодняшний день большинство моих отчетов были простыми, поэтому я мог сам легко их создавать. Но, будучи новичком в sql / dlinq, я не могу найти следующий путь:

var closingStock =
    (from p in session.Query<Product>()
    select new
    {
        p.Id,
        p.Name,
        p.Batch,
        p.Rate,
        ClosingStock = p.Quantity - p.AllocatedQuantity,
        p.DivisionId
    }).ToList();

var distributedQuantityAfterPeriod =
    (from i in session.Query<OutwardInvoiceItem>()
    where i.ParentInvoice.Date > ToDate 
    select new
    {
        Id = i.Product.Id,
        DistributedAfter = i.Quantity
    }).ToList();

var distributedQuantityInPeriod =
    (from i in session.Query<OutwardInvoiceItem>()
    where i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate
    select new
    {
        Id = i.Product.Id,
        Distributed = i.Quantity
    }).ToList();

var receivedQuantityAfterPeriod =
    (from i in session.Query<InwardInvoiceItem>()
    where i.ParentInvoice.Date > ToDate
    select new
    {
        Id = i.Product.Id,
        ReceivedAfter = i.Quantity
    }).ToList();

var receivedQuantityInPeriod =
    (from i in session.Query<InwardInvoiceItem>()
    where i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate
    select new
    {
        Id = i.Product.Id,
        Received = i.Quantity
    }).ToList();

Как видите, я пытаюсь создать отчет о движении инвентаря за конкретную дату. У меня есть следующие проблемы:
1. Как я могу уменьшить пять запросов? Возможно ли это?
2. Как можно объединить данные, предоставленные этими запросами, в одну таблицу, которая сгруппирована по идентификатору продукта и суммирована по столбцам, связанным с количеством? На данный момент я использую петли, которые очень медленные.

Что я использую:
C # 4, nHibernate, Sqlite

Любая помощь будет очень высоко оценена.

С уважением, Yogesh.

1 Ответ

1 голос
/ 12 октября 2011
  1. , чтобы уменьшить количество циклов, используйте .Future() вместо .List()

  2. пусть все запросы возвращают

    group i by i.Id into g
    select new
    {
        Id = g.Key,
        Quantity = g.Sum(x => x.Quantity)
    }).Future();
    

и сделать

var alltogether = groupedDistributedQuantityAfterPeriod
    .Concat(groupedDistributedQuantityInPeriod)
    .Concate(...);

from g in alltogether
group g by g.key into all
select new
{
    Id = all.Key,
    Quantity = all.Sum(x => x.Quantity)
};

Обновление:

Вы можете уменьшить количество запросов с помощью

from i in session.Query<OutwardInvoiceItem>()
where (i.ParentInvoice.Date > ToDate) || (i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate)
select ...

from i in session.Query<InwardInvoiceItem>()
where (i.ParentInvoice.Date > ToDate) || (i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate)
select ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...