mvc5 create new select from query - sql

this is the query :
var data = db.tableone.Where(a => a.type == 1).Select(u => new {id = u.id, type = u.type,newcolumnnotexistindatabase = "test"} );
return data.ToList();
while there is 5 column by the type of 1, it should show me in list
id, type -- newcolumnnotexistindatabase
1 , 1 --test
2 , 1 --test
3 , 1 --test
4 , 1 --test
5 , 1 --test
ERORR:
can not implicitly convert type 'System.Collections.Generic.List<<

The problem is that, you can't return anonymous type. If return type of your function is List<<AnyClass>> , your linq query should be like this:
var data = db.tableone
.Where(a => a.type == 1)
.Select(u => new AnyClass
{
id = u.id,
type = u.type,
newcolumnnotexistindatabase = "test"
} );
return data.ToList();

Related

I try to get results from table with multiple where and/or clauses Query Builder

i try to get results from table with multiple where and/or clauses.
My SQL statement is:
select *
from ceri.movimentacao_parcela_repasse mpr
inner join ceri.movimentacao_parcela mp on (mp.id_movimentacao_parcela = mpr.id_movimentacao_parcela)
inner join ceri.pedido p on (p.id_pedido = mp.id_pedido)
inner join ceri.produto pd on (pd.id_produto = p.id_produto)
where mpr.id_repasse = 4
and mpr.in_repasse_aberto = 'S'
and ( (pd.id_grupo_produto = 1 and p.id_situacao_pedido_grupo_produto = 7 ) or (pd.id_grupo_produto = 2
and p.id_situacao_pedido_grupo_produto = 17) )
My Code in Laravel is:
first attempt
->where('movimentacao_parcela_repasse.id_repasse', '=', DB::raw('4'))
->where('movimentacao_parcela_repasse.in_repasse_aberto', '=', DB::raw('\'S\''))
->where(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('1')) //-- 1 Pesquisa
->where('produto.id_situacao_pedido_grupo_produto',DB::raw('7')); // 7 -- Finalizado
})
->orWhere(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('2')) //2 Certidão /
->where('produto.id_situacao_pedido_grupo_produto',DB::raw('17')); //17 -- Finalizado
});
// RESULT
and ("produto"."id_grupo_produto" = 1 and "pedido"."id_situacao_pedido_grupo_produto" = 7) or ("produto"."id_grupo_produto" = 2 and "pedido"."id_situacao_pedido_grupo_produto" = 17)
second attempt
->where('movimentacao_parcela_repasse.id_repasse', '=', DB::raw('4'))
->where('movimentacao_parcela_repasse.in_repasse_aberto', '=', DB::raw('\'S\''))
->where(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('1'))
->where('pedido.id_situacao_pedido_grupo_produto',DB::raw('7'))
->orWhere(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('2'))
->where('pedido.id_situacao_pedido_grupo_produto',DB::raw('17'));
});
});
// RESULT
and ("produto"."id_grupo_produto" = 1 and "pedido"."id_situacao_pedido_grupo_produto" = 7 or ("produto"."id_grupo_produto" = 2 and "pedido"."id_situacao_pedido_grupo_produto" = 17))
I do not want the way i wanted
and ( (pd.id_grupo_produto = 1 and p.id_situacao_pedido_grupo_produto = 7 ) or (pd.id_grupo_produto = 2 and p.id_situacao_pedido_grupo_produto = 17) )
Try this:
->where('movimentacao_parcela_repasse.id_repasse', '=', DB::raw('4'))
->where('movimentacao_parcela_repasse.in_repasse_aberto', '=', DB::raw('\'S\''))
->where(function($query) {
->where(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('1'))
->where('pedido.id_situacao_pedido_grupo_produto',DB::raw('7'))
})
->orWhere(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('2'))
->where('pedido.id_situacao_pedido_grupo_produto',DB::raw('17'));
});
});

How to select from a table by date using linqq

I have a table with products that can be in different locations to be submited to a rework task, but i need to pick only the most recent one based on the product.
I have the following table:
ID Tag Location task Date
1 1 A T1 2016/06/01
2 1 B T1 2016/07/01
3 2 A T1 2016/06/01
4 2 A T2 2016/07/01
i ned the select the row of the Tags with most recent Date to have in output the row with ID 2 and ID 4.
What is the correct linq query for that?
First group by tag then select max date
var result = db.Table.GroupBy(i => i.Tag).Select(i => new
{
Tag = i.Key,
Date = i.Max(t => t.Date)
}).ToList();
Updated 1 (Comment 1)
var result = (from x in db.Table
join z in (db.Table.GroupBy(i => i.Tag).Select(i => new
{
Tag = i.Key,
Date = i.Max(t => t.Date)
})
) on new { A = x.Tag, B = x.Date} equals { A = z.Tag, B = z.Date }
select x).ToList();
Update 2 (Comment 2)
var result = (from x in db.Table
join z in (db.Table.GroupBy(i => new { i.Tag, i.Task }).Select(i => new
{
Tag = i.Key.Tag,
Task = i.Key.Task,
Date = i.Max(t => t.Date)
})
) on new { A = x.Tag, B = x.Date, C = x.Task} equals { A = z.Tag, B = z.Date, C = z.Task }
select x).ToList();

Get Rank from from Total LINQ Query

I have two tables.First is CompetitionUsers and Competitionpoints.
There is foreign key relationship between tables with ParticipateID.
In CompetitionPoints Table there are points different points for multiple participateID.So I want to fetch Total Points and the Rank based on total points.So if there is multiple same total points for one participateID, the rank for that participateid should be same .Its same like student Total marks and Rank from that Mark.
Here is my code.
var competitionusers = (from c in db.CompetitionUsers
group c by new { c.ParicipateId, c.CompetitionPoints.FirstOrDefault().Points }
into g orderby g.Key.Points descending select
new { Points = db.CompetitionPoints.Where
(x => x.ParticiapteId == g.FirstOrDefault().ParicipateId).Sum(x => x.Points),
Rank = (from o in db.CompetitionUsers
group o by o.CompetitionPoints.FirstOrDefault().Points into l
select l).Count(s => s.Key > db.CompetitionPoints.
Where(x => x.ParticiapteId == g.FirstOrDefault().ParicipateId).Sum(x => x.Points)) + 1,
}).Where(x => x.Points != null).OrderByDescending(x => x.Points).AsQueryable();
If I understand your data model correctly, I think you could simplify to something like this:
var result = db.CompetitionUsers
// group by total points
.GroupBy(cu => cu.CompetitionPoints.Sum(cp => cp.Points))
// order by total points descending
.OrderByDescending(g => g.Key)
// calculate rank based on position in grouped results
.SelectMany((g, i) => g.Select(cu => new { Rank = i+1, TotalPoints = g.Key, CompetitionUser = cu }));
IQueryable<CompetitionLaderMadel> competitionUsers;
competitionUsers = (from c in db.CompetitionUsers
select new CompetitionLaderMadel
{
CompetitionName = c.Competition.CompetitionName,
CompetitionId = c.CompetitionId,
Points = db.CompetitionPoints.Where(x => x.ParticiapteId == c.ParicipateId).Sum(x => x.Points),
IsFollow = db.CrowdMember.Any(x => x.Following == userid && x.UserCrowd.UserID == c.UserId && x.Status != Constants.Deleted),
}).Where(x => x.Points != null && x.UserId != null).OrderByDescending(x => x.Points);
And then Wrote this Query
var q = from s in competitionUsers
orderby s.Points descending
select new
{
CompetitionName = s.CompetitionName,
CompetitionId = s.CompetitionId,
HeadLine = s.HeadLine,
UserId = s.UserId,
Points = s.Points,
Image = s.Image,
IsFollow = s.IsFollow,
UserName = s.UserName,
Rank = (from o in competitionUsers
where o.Points > s.Points
select o).Count() + 1
};

translating sql statement to linq

I have a working sql statement and want it as linq statement or linq methode chain.
My statement is:
SELECT T1.*
FROM (SELECT Col1, MAX(InsertDate) as Data
FROM Zugbewegungsdaten
GROUP BY Loknummer) as temp JOIN T1
ON (T1.Col1= temp.Col1
AND Zugbewegungsdaten.InsertDate= temp.Date)
WHERE Col3=1
ORDER BY Loknummer
Can anybody help me to translate it?
Edit after comment:
Ok, my result for the inner select:
var maxResult = (from data in context.T1
group data by data.Col1
into groups
select new
{
Train = groups.Key,
InsertDate= groups.Max( arg => arg.InsertDate)
}) ;
I tried the join like this:
var joinedResult = from data in context.T1
join gdata in maxResult on new
{
data.Col1,
data.InsertDate
}
equals new
{
gdata.Col1,
gdata.InsertDate
}
select data;
But i get a compiler error by the join that the typeargument are invalid.
In the case that the join works i whould use a where to filter the joinedResult.
var result = from data in joinedResult
where data.Col3 == true
select data;
After much more "try and error", I got this version it looks like it works.
var joinedResult = ( ( from data in context.T1
group data by data.Col1
into g
select new
{
Key= g.Key,
Date = g.Max( p => p.InsertDate)
} ) ).Join( context.T1,
temp => new
{
Key = temp.Key,
InsertDate = temp.Date
},
data => new
{
Key = data.Col1,
InsertDate = data.InsertDate
},
( temp,
data ) => new
{
temp,
data
} )
.Where( arg => arg.data.Col3)
.OrderBy( arg => arg.data.Col1)
.Select( arg => arg.data );
Could it be that i have to set the same property names (Key, InsertDate) by joins over multi columns?

How to create list of anonymous types in select clause?

Here is one of queries I am using in my project:
var carQuery = from cars in context.Cars
.Where(c => c.CarID==3)
from stockTypes in context.StockTypes
.Where(st => cars.StockTypeId == st.StockTypeID).DefaultIfEmpty()
from carUnit in context.Car_Units
.Where(cu => cu.CarId == cars.CarID).DefaultIfEmpty()
from carAttributes in context.Car_Attributes
.Where(ca => ca.CarId == cars.CarID).DefaultIfEmpty()
from attribute in context.Attributes
.Where(attr => attr.AttributeId==carAttributes.AttributeId).DefaultIfEmpty()
select new
{
CarID = cars.CarID,
CarName = cars.CarName,
CarDescription = cars.CarDescription,
StockType = (stockTypes == null) ? null : new
{
StockTypeID = stockTypes.StockTypeID,
StockName = stockTypes.StockName
},
IsActive = cars.IsActive,
IsCab = cars.IsCab,
Unit = (carUnit == null) ? null : new
{
Id = carUnit.UnitId,
Name = carUnit.Unit.UnitName
},
Attributes = attribute
};
If the context.Attributes returns multiple rows, the whole resultset also returning multiple rows.
Is there any possibility to return a single car type with multiple attributes as a list of attributes to the car??
Please help.
Thanks,
Mahesh
You just need to move the attribute query inside the result set:
var carQuery = from cars in context.Cars
.Where(c => c.CarID==3)
from stockTypes in context.StockTypes
.Where(st => cars.StockTypeId == st.StockTypeID).DefaultIfEmpty()
from carUnit in context.Car_Units
.Where(cu => cu.CarId == cars.CarID).DefaultIfEmpty()
from carAttributes in context.Car_Attributes
.Where(ca => ca.CarId == cars.CarID).DefaultIfEmpty()
select new
{
CarID = cars.CarID,
CarName = cars.CarName,
CarDescription = cars.CarDescription,
StockType = (stockTypes == null) ? null : new
{
StockTypeID = stockTypes.StockTypeID,
StockName = stockTypes.StockName
},
IsActive = cars.IsActive,
IsCab = cars.IsCab,
Unit = (carUnit == null) ? null : new
{
Id = carUnit.UnitId,
Name = carUnit.Unit.UnitName
},
Attributes =
from attribute in context.Attributes
.Where(attr => attr.AttributeId==carAttributes.AttributeId).DefaultIfEmpty()
.GroupBy(at => at.AttributeId)
select attribute
};