Linq to sql query fails - linq-to-dataset

I am having problem in executing a linq to sql query. Please have a look.
Here is my code:
SELECT c.client_name,
n.instrument_group_id,
n.trade_date,
sum(n.buy_qty) AS TotBuyQty,
sum(convert(float,n.buy_value) + convert(float,n.buy_brokerage)) AS TotBuyVal,
sum(n.sell_qty) AS TotSellQty,
sum(convert(float,n.sell_value) - convert(float,n.sell_brokerage)) AS TotSellVal,
sum(convert(float,n.sell_value) - convert(float,n.sell_brokerage))- sum(convert(float,n.buy_value) + convert(float,n.buy_brokerage)) AS ProfitLoss
FROM nse_fo_transaction AS n
LEFT JOIN client_master AS c ON n.client_id = c.client_id
WHERE n.client_id = 5
AND n.trade_date BETWEEN '09/01/2012' AND '09/19/2012'
GROUP BY c.client_name,
n.instrument_group_id,
n.trade_date
ORDER BY n.trade_date

How's this?
from d in dps_admin_user
join c in dps_admin_role on d.user_id equals c.user_id into gcs
from c2 in gcs.DefaultIfEmpty()
group d.firstname by c2.parent_id into gfns
where gfns.Any()
orderby gfns.Count()
select gfns
I just threw it together in LINQPad. Not very meaningful I must say, but it contains your required operators.
Why do you need such an example??
This is roughly the query you want. I couldn't test it, but it should be fairly close.
var query =
from n in nse_fo_transaction
where n.client_id == 5
where n.trade_date >= d0 && n.trade_date < d1
join c0 in client_master on n.client_id equals c.client_id into cs
from c in cs.DefaultIfEmpty()
group new { n, c } by new
{
c.client_name,
n.instrument_group_id,
n.trade_date,
} into gs
orderby gs.Key.trade_date
select new
{
gs.Key.client_name,
gs.Key.instrument_group_id,
gs.Key.trade_date,
TotBuyQty = gs.Sum(x =>
(float)x.n.buy_qty),
TotBuyVal = gs.Sum(x =>
(float)x.n.buy_value
+ (float)x.n.buy_brokerage),
TotSellQty = gs.Sum(x =>
(float)x.n.sell_qty),
TotSellVal = gs.Sum(x =>
(float)x.n.sell_value
- (float)x.n.sell_brokerage),
ProfitLoss = gs.Sum(x =>
(float)x.n.sell_value
- (float)x.n.sell_brokerage
- (float)x.n.buy_value
+ (float)x.n.buy_brokerage)
};

Dim query = (From n In tblNseFo.AsEnumerable _
Where n!client_id = intClientID _
Group Join c In tblClient _
On n!client_id Equals c!client_id Into cs = Group _
From c In cs.DefaultIfEmpty _
Group n, c By _
c!client_name, n!instrument_group_id, n!trade_date Into gs = Group _
Order By trade_date _
Select New With { _
.client_name = client_name, _
.instrument_group_id = instrument_group_id, _
.trade_date = trade_date, _
.TotBuyQty = gs.Sum(Function(x) x.n!buy_qty), _
.TotSellQty = gs.Sum(Function(x) x.n!sell_qty), _
.TotBuyVal = gs.Sum(Function(x) x.n!buy_value) + gs.Sum(Function(x) x.n!buy_brokerage), _
.TotSellVal = gs.Sum(Function(x) x.n!sell_value) - gs.Sum(Function(x) x.n!sell_brokerage), _
.ProfitLoss = (gs.Sum(Function(x) x.n!sell_value) - gs.Sum(Function(x) x.n!sell_brokerage)) - _
(gs.Sum(Function(x) x.n!buy_value) + gs.Sum(Function(x) x.n!buy_brokerage))})

Related

How to get list of results in Linq

I'm taking a list of counts, averaging and returning all results according to the condition. Looks like my command is too erroneous. I don't know how to do it yet.
I have tables:
var qr = (from Product c in _context.Products
join o in _context.RatingProducts on c.ID equals o.IDProduct
where c.Status == true
orderby c.NumProduct
group o by c.ID into g
select new {
ProductId = g.Key,
CountID = g.Count(),
//SumID = g.Sum(s => s.StarRating).ToString(),
AveragedID = g.Count() > 0 ? g.Average(x => x.StarRating) : 0
}).ToList();
var getqr = _context.Products.Where(a => a.Status).ToList();
int count = 0;
double averaged = 0;
foreach (var item in getqr)
{
int key = item.ID;
var id = qr.Where(x => x.ProductId == key).FirstOrDefault();
if(id != null)
{
count = id.CountID;
averaged = Math.Round(id.AveragedID,1);
}
var productquery = item;
}
var query = from c in qr
join p in getqr on c.ProductId equals p.ID
select new ProductQuery
{
ID = p.ID,
IDProduct = p.IDProduct,
CategoryID = p.CategoryID,
NumProduct = p.NumProduct,
Name = p.Name,
Status = p.Status,
Price = p.Price,
PriceOld = p.PriceOld,
ContentsSmall = p.ContentsSmall,
Contents = p.Contents,
Images = p.Images,
CountID = count,
//SumID = c.SumID,
AveragedID = averaged,
};
return query.ToList();
However when I debug, it shows only one result with row ID = 1. I want to display list: count, average results of table 1. Tks.
As far as I understand you should make LEFT JOIN here, so need to add DefaultIfEmpty in the initial query, and slightly change average counting logic.
Something like this, should work:
var qr = (from Product c in _context.Products
join o in _context.RatingProducts on c.ID equals o.IDProduct into productRatings
from pr in productRatings.DefaultIfEmpty()
where c.Status == true
orderby c.NumProduct
group o by c.ID into g
select new {
ProductId = g.Key,
CountID = g.Count(),
AveragedID = g.Average(x => x == null ? 0 : x.StarRating)
}).ToList();

Linq query dynamic

I've this linq query:
var query = (from l in _contexto.lineasencargos
join a in _contexto.articulos on l.IDARTICULO equals a.IDARTICULO
join af in _contexto.articulofamilia on a.IDARTICULO equals af.IDARTICULO
join f in _contexto.familias on af.IDFAMILIA equals f.IDFAMILIA
join e in _contexto.encargos on l.IDENCARGO equals e.IDENCARGO
where e.FECHAHORAENCARGOS >= _finder.FechaDe &&
e.FECHAHORAENCARGOS <= _finder.FechaA &&
e.FECHAHORARECOGERENCARGOS >= _finder.FechaRecogerDe &&
e.FECHAHORARECOGERENCARGOS <= _finder.FechaRecogerA &&
e.clientes.RAZONSOCIALCLIENTE.Contains(_finder.Cliente)
group l by new { l.IDARTICULO, l.CANTIDADLINEAENCARGO,a.DESCRIPCIONARTICULO,f.DESCRIPCION,f.IDFAMILIA }
into g
select new listaEncargosAgrupados
{
IdArticulo=(int)g.Key.IDARTICULO,
DescripcionArticulo=g.Key.DESCRIPCIONARTICULO,
IdFamilia=g.Key.IDFAMILIA,
DescripcionFamilia=g.Key.DESCRIPCION,
SumaCantidad = (decimal)g.Sum(x => x.CANTIDADLINEAENCARGO),
SumaPrecio = (decimal)g.Sum(x => x.PRECIOLINEAENCARGO),
Total = (decimal)((decimal)g.Sum(x => x.CANTIDADLINEAENCARGO) * g.Sum(x => x.PRECIOLINEAENCARGO))
});
and i need create a condition in Where, that filter dynamically:
if (_finder.IdTienda > 0)
{
query = query.Where(x=>x.IDTIENDA == _finder.IdTienda);
}
But this Where it is not correct because IDTIENDA is contained in _context.encargos and not in listaEncargosAgrupados
How i can revolve this problem?
Thanks
Add e into grouping statement and IDTIENDA list into the result:
var query = (from l in _contexto.lineasencargos
join a in _contexto.articulos on l.IDARTICULO equals a.IDARTICULO
join af in _contexto.articulofamilia on a.IDARTICULO equals af.IDARTICULO
join f in _contexto.familias on af.IDFAMILIA equals f.IDFAMILIA
join e in _contexto.encargos on l.IDENCARGO equals e.IDENCARGO
where e.FECHAHORAENCARGOS >= _finder.FechaDe &&
e.FECHAHORAENCARGOS <= _finder.FechaA &&
e.FECHAHORARECOGERENCARGOS >= _finder.FechaRecogerDe &&
e.FECHAHORARECOGERENCARGOS <= _finder.FechaRecogerA &&
e.clientes.RAZONSOCIALCLIENTE.Contains(_finder.Cliente)
group new { l, e} by new { l.IDARTICULO, l.CANTIDADLINEAENCARGO,a.DESCRIPCIONARTICULO,f.DESCRIPCION,f.IDFAMILIA }
into g
select new { Result = new listaEncargosAgrupados
{
IdArticulo=(int)g.Key.IDARTICULO,
DescripcionArticulo=g.Key.DESCRIPCIONARTICULO,
IdFamilia=g.Key.IDFAMILIA,
DescripcionFamilia=g.Key.DESCRIPCION,
SumaCantidad = (decimal)g.Sum(x => x.l.CANTIDADLINEAENCARGO),
SumaPrecio = (decimal)g.Sum(x => x.l.PRECIOLINEAENCARGO),
Total = (decimal)((decimal)g.Sum(x => x.l.CANTIDADLINEAENCARGO) * g.Sum(x => x.l.PRECIOLINEAENCARGO))
},
IDTIENDAs = new HashSet<int>(from x in g
let id = x.e.IDTIENDA
where id.HasValue
select (int)id.Value)
});
...
if (_finder.IdTienda > 0)
{
query = query.Where(x => x.IDTIENDAs.Contains (_finder.IdTienda));
}
var query1 = query.Select(x => x.Result);
Finally the solution to my problem was to employ executestorequery in the context of my EF, and creat a SQL query :
List<ListaEncargosAgrupados> lista;
string queryString = #"SELECT l.IDARTICULO,a.DESCRIPCIONARTICULO,f.DESCRIPCION descripcionFamilia,f.IDFAMILIA,sum(l.CANTIDADLINEAENCARGO) sumaCantidad,avg(l.PRECIOLINEAENCARGO)
sumaPrecio,sum(l.CANTIDADLINEAENCARGO)*avg(l.PRECIOLINEAENCARGO) Total " +
"FROM lineasencargos l,articulos a,articulofamilia af,familias f,encargos e " +
"where a.IDARTICULO=l.IDARTICULO and a.IDARTICULO=af.IDARTICULO " +
"and af.IDFAMILIA=f.IDFAMILIA and l.IDENCARGO=e.IDENCARGO ";
if (_finder.IdTienda > 0)
{
queryString = queryString + " and e.idtienda=" + _finder.IdTienda;
}
queryString = queryString + " group by l.IDARTICULO,a.DESCRIPCIONARTICULO,f.DESCRIPCION,f.IDFAMILIA order by a.DESCRIPCIONARTICULO ";
var salidaQuery = _contexto.ExecuteStoreQuery<ListaEncargosAgrupados>(queryString).AsQueryable().ToList();
lista = salidaQuery;

vb.net Linq statement to c#

I am trying to convert this statement in vb.net Linq:
Dim exchangeTradingCapacity = (
From ts In db_context.TRADE_SUMMARies _
Join el In db_context.EXECUTION_LISTs On ts.TRADE_ID Equals el.TRADE_ID _
And ts.TRADE_PART_INDEX Equals el.TRADE_PART_INDEX _
And ts.VERSION Equals el.TRADE_VERSION _
Join oe In db_context.ORDER_EXECUTIONs On oe.EXECUTION_ID Equals ts.CONTRIBUTOR_REF _
Where rootOrdersToInclude.Distinct.Contains(el.ROOT_ORDER_ID) _
And el.TRADE_VERSION = (From el1 In db_context.EXECUTION_LISTs _
Where el1.TRADE_ID = el.TRADE_ID _
And el1.TRADE_PART_INDEX = el.TRADE_PART_INDEX _
And el1.ROOT_ORDER_ID = el.ROOT_ORDER_ID _
Select el1.TRADE_VERSION).Max() _
Group oe By Key = oe.EXCHANGE_TRADING_CAPACITY Into Group _
Select Key
).ToList
My attempt to convert it to c# has thus far been unsuccessful:
var exchangeTradingCapacity =
(from ts in dbContext.TRADE_SUMMARies
join e1 in dbContext.EXECUTION_LISTs on
new
{
ts.TRADE_ID,
ts.TRADE_PART_INDEX,
ts.VERSION
}
equals
new
{
e1.TRADE_ID,
e1.TRADE_PART_INDEX,
VERSION = e1.TRADE_VERSION
}
join oe in dbContext.ORDER_EXECUTIONs on ts.CONTRIBUTOR_REF equals oe.EXECUTION_ID
where rootOrdersToInclude.Distinct().Contains(e1.ROOT_ORDER_ID) &&
e1.TRADE_VERSION == (from el1 in dbContext.EXECUTION_LISTs
where el1.TRADE_ID == el.TRADE_ID &&
el1.TRADE_PART_INDEX == el.TRADE_PART_INDEX &&
el1.ROOT_ORDER_ID == el.ROOT_ORDER_ID
select el1.TRADE_VERSION).Max()
group oe by oe.EXCHANGE_TRADING_CAPACITY into theKey
select theKey
).ToList();
It appears that for some reason, 'el' is out of scope when inside the subquery. Can someone point me to the error of my ways? It seems like this should work.
You don't have an alias el (letter L), only the alias e1 (number 1).

linq union group by undefined

I am calling the following function from a web service but can't get the object defined.
Dim x = (From a In _db.report _
Select ep = a.CurrentReport, CuCy = a.Current_Cycle) _
.Union _
(From b In _db.Counts _
Group b By b.Year, b.Report Into k() _ <--------(this is undefined)
Select ep = b.Report, CucY = b.Year).ToList().Take(10)
Is this the correct way to do a group by in a union query?
I would appreciate any help.
The Grouping syntax in VB is slightly different than C#. The Group By requires you to state Into Group rather than aliasing the new structure. See if the following works for you:
Dim x = (From a In _db.report _
Select ep = a.CurrentReport, CuCy = a.Current_Cycle) _
.Union _
(From b In _db.Counts _
Group By b.Year, b.Report Into Group _ <--------(this is undefined)
Select ep = Key.Report, Key.Year).ToList().Take(10)
Since you don't appear to be aggregating in the second query, you might be able to just do a distinct instead:
From b in _db.Counts
Select b.Report, B.Year
Distinct

Linq syntax join and group

Hello I need to join two tables (MainTransaction and Subtransaction), the problem here is I also want to get all the record of Maintransaction that's not in the Subtransaction, I am stuck in this part, how can I achieve this ?
protected object SelectMainTbl()
{
var mainIdAndSum = from st in t.subtransaction
group st by st.MainTransactionId into g
select new
{
Sum = (from r in g
select r.Amount).Sum(),
MainId = g.Key
};
var mainTbl = from main in t.maintransaction
join sub in mainIdAndSum on main.MainTransactionId equals sub.MainId
where main.IsEnabled == true && (sub.Sum - main.Amount != 0)
select main;
return mainTbl;
}
I think this is the query that you want:
from mt in t.maintransaction
join st in t.subtransaction
on mt.MainTransactionId equals st.MainTransactionId
into sts
where mt.IsEnabled
where sts.Sum(x => x.Amount) - mt.Amount != 0
select new
{
MainTransaction = mt,
Subtransactions = sts,
};

Resources