Count resulted records using linq to sql - asp.net

i use linq to sql query for retrive records from database.
i use a query,for binding a gridview.
protected void grdBind()
{
try
{
EventManagerDataContext db = new EventManagerDataContext();
var z = (from x in db.EMR_EVENTs
join y in db.EMR_CLIENTs on x.ClientID equals y.ClientID
where y.ClientID==x.EventID
select x.EventID).Count();
var q = from a in db.EMR_CLIENTs
join b in db.EMR_EVENTs on a.ClientID equals b.ClientID
join c in db.EMR_ACCOUNTs on a.ClientID equals c.ClientID
join d in db.EMR_SUBSCRIPTIONs on c.Account_ID equals d.Account_ID
join f in db.EMR_SUBSCRIPTION_KINDs on d.Subscription_kind_ID equals f.Subscription_kind_ID
select new
{
Customer = a.Name,
Events = z,
TurnOver = f.Monthly_Fee,
StartDate = d.Start_Date,
EndDate = d.End_Date,
CreteDate = d.Create_Date,
ClientID = a.ClientID,
EventID = b.EventID,
SubscriptionID = d.Subscription_ID,
Subscription_kind_ID=f.Subscription_kind_ID,
Account_ID=c.Account_ID,
};
grid.DataSource = q.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
catch
{
throw;
}
}
and i recieve this output for that,
i recieve this output for this query but i don't want this output ,
i want like this output.
clientname events
ketan 18
monika 12
and others records so on means i recieve here client name 9 times and he created events but i want some of events and client name only one time
means i want only one name of client and total number of events,i am new to linq to sql.
so what is the changes in code..?

when you are using join syntax in query you do not need to use 'where'
then change your query to :
var z = (from x in db.EMR_EVENTs
join y in db.EMR_CLIENTs on x.ClientID equals y.ClientID
select x.EventID).Count();

i found solution .here
ans also use with this.useful link
here is my solution.
EventManagerDataContext db = new EventManagerDataContext();
var q = from a in db.EMR_CLIENTs
join b in db.EMR_EVENTs on a.ClientID equals b.ClientID into z
join c in db.EMR_ACCOUNTs on a.ClientID equals c.ClientID
join d in db.EMR_SUBSCRIPTIONs on c.Account_ID equals d.Account_ID
join f in db.EMR_SUBSCRIPTION_KINDs on d.Subscription_kind_ID equals f.Subscription_kind_ID
select new
{
Customer = a.Name,
Events =z.Where(b =>b.ClientID==a.ClientID).Count(),
TurnOver = f.Monthly_Fee,
StartDate = d.Start_Date,
EndDate = d.End_Date,
CreteDate = d.Create_Date,
ClientID = a.ClientID,
SubscriptionID = d.Subscription_ID,
Subscription_kind_ID=f.Subscription_kind_ID,
Account_ID=c.Account_ID,
};
grid.DataSource = q.ToList();

Related

How to pass a SQL query to Entity Framework

I am creating a report and need to pass a query from SQL Server to Entity Framework.
The query is:
SELECT
contas_receber.id, pessoa.nome, contas_receber.vencimento,
contas_receber.valor_pago, contas_receber.observacao, pessoa.estado
FROM
contas_receber
INNER JOIN
pessoa ON contas_receber.pessoa_id = pessoa.id
INNER JOIN
classificacoes ON classificacoes.id = pessoa.classificacao_id
LEFT OUTER JOIN
servicos ON servicos.id = contas_receber.servico_id
LEFT OUTER JOIN
produto ON produto.id = contas_receber.venda_id
WHERE
(contas_receber.quitado = 0)
AND (CAST(contas_receber.vencimento AS date) >= #datavenc1)
AND (CAST(contas_receber.vencimento AS DATE) <= #datavenc2)
AND (classificacoes.id = #idclassificacao OR #idclassificacao IS NULL)
AND (servicos.id = #idservico OR #idservico IS NULL)
AND (servicos.plano = #tiposervico OR #tiposervico IS NULL)
AND (produto.id = #idproduto OR #idproduto IS NULL)
AND (pessoa.status_financeiro = #statusfinanceiro OR #statusfinanceiro IS NULL)
AND (pessoa.estado = #estado OR #estado IS NULL)
ORDER BY
contas_receber.vencimento
How would you stay in Entity Framework?
what I've done so far:
var contas = from c in _context.ContasReceber
join p in _context.Pessoas on c.PessoaId equals p.Id
join cl in _context.Classificacoes on p.ClassificacaoId equals cl.Id
join ps in _context.PlanosServicos on c.ServicoId equals ps.Id
join pr in _context.Produtos on c.IdVenda equals pr.Id
join tp in _context.TiposProdutos on pr.TiposProdutosId equals tp.Id
where c.Vencimento >= Inicial && c.Vencimento <= Final && (cl.Id == classificacoes || classificacoes is null)
The courses are different because the seats are different, but the sense is the same. My biggest problem is in the conditional whare, when you have to verify that the variable is null
using
Database.SqlQuery():
The Database class represents the underlying database and provides various methods to deal with the database. The Database.SqlQuery() method returns a value of any type.
//Example refer this link
using (var ctx = new SchoolDBEntities())
{
string studentName = ctx.Database.SqlQuery<string>("Select studentname from Student
where studentid=1").FirstOrDefault();
}

Accessing all properties from child tables by innerjoin to use on asp:GridView

I wrote this method to use it as SelectMethod in asp GridView. I want to access all the properties in child tables(EmployeeCourses ,EmployeeLanguages ,EmployeeSkills ) as well,but I cannot select y , z , w in the query as their type mismatch.
What option do I have here?
public List<EmployementRequest> requestsGrid_GetData()
{
var ukn = new UKN_DBNAMEEntities();
var query = (from x in ukn.EmployementRequests
join y in ukn.EmployeeCourses on x.PKEmploymentRequest equals y.FKEmployementRequest
join z in ukn.EmployeeLanguages on x.PKEmploymentRequest equals z.FKEmploymentRequest
join w in ukn.EmployeeSkills on x.PKEmploymentRequest equals w.FKEmploymentRequest
select x).ToList();
return query.ToList();
}
You need to create an anonymous type or a custom class(DTO) to save your projection, in your case should be a DTO because you want to return the result, so you need to define a class with 4 properties to save those entities:
public class EmployementDTO
{
//Define properties here
public EmployementRequest EmployementRequest{get;set;}
//..
}
And then:
public List<EmployementDTO> requestsGrid_GetData()
{
var ukn = new UKN_DBNAMEEntities();
var query = (from x in ukn.EmployementRequests
join y in ukn.EmployeeCourses on x.PKEmploymentRequest equals y.FKEmployementRequest
join z in ukn.EmployeeLanguages on x.PKEmploymentRequest equals z.FKEmploymentRequest
join w in ukn.EmployeeSkills on x.PKEmploymentRequest equals w.FKEmploymentRequest
select new EmployementDTO{EmployementRequest=x,EmployeeCourse=y,...);
return query.ToList();
}

Group newly made parameter values in linq to sql

I am trying to group newly made key values but i'm not getting it to work.
This is the code
Dim result = From v In dc.tbl_voertuigs
Join tv In dc.tbl_type_voertuigs On tv.pk_type_voertuig Equals v.fk_type_voertuig
Join tbc In dc.tbl_tebehalencertificaats On tbc.pk_tebehalencertificaat Equals v.fk_tebehalencertificaat
Where tbc.naam_certificaat = subquery2
Select New Voertuig With
{
.p_voertuigid = v.fk_type_voertuig,
.p_voertuigomschr = tv.type + " -- " + tv.merk
}
I would like to group on .p_voertuigid. I already tried some options without any result. I hope someone here can help me.
Thanks in advance!
I think i am almost there, but now i'm getting a new exception:
Value of type system.collections.generic.list(of <anonymoustype>) cannot be converted
to system.collections.generic.list(of tbl_voertuig)
This is my new code
Dim result = (From v In dc.tbl_voertuigs
Join tv In dc.tbl_type_voertuigs On tv.pk_type_voertuig Equals v.fk_type_voertuig
Join tbc In dc.tbl_tebehalencertificaats On tbc.pk_tebehalencertificaat Equals v.fk_tebehalencertificaat
Where tbc.naam_certificaat = subquery2
Group By v = New Voertuig With
{
.p_voertuigid = v.fk_type_voertuig,
.p_voertuigomschr = tv.type + " -- " + tv.merk
} Into grp = Group).ToList
Return result
I found the answer, this is the final code and it works
Dim result = From v In dc.tbl_voertuigs
Join tv In dc.tbl_type_voertuigs On tv.pk_type_voertuig Equals v.fk_type_voertuig
Join tbc In dc.tbl_tebehalencertificaats On tbc.pk_tebehalencertificaat Equals v.fk_tebehalencertificaat
Where tbc.naam_certificaat = subquery2
Group By v = New Voertuig With
{
.p_voertuigid = v.fk_type_voertuig,
.p_voertuigomschr = tv.type + " -- " + tv.merk
} Into grp = Group _
Select v
Return result.ToList
I hope this can help someone who has the same problem in the future
Grtz
Yannick

Entity Framework query joins and group by issue

Please correct the query
IN PL/SQL
SELECT a.MENU_ID, a.menu_label, a.menu_value
FROM tbl_ims_menu a, TBL_IMS_ROLE_ASSIGNED_MENU b,TBL_IMS_USER_ROLE_PRIVILEGES c
WHERE a.menu_id = b.menu_id AND b.urole_id = c.granted_role
AND c.user_id = '3' AND a.menu_master <> '0'
AND a.menu_status = 'Active'
GROUP BY a.menu_id, a.menu_label, a.menu_value
query is working fine there is some issue when rewrite in Entity framework
check the following query
List<TBL_IMS_MENU> listSubMenu = (from m in db.TBL_IMS_MENU
join ra in db.TBL_IMS_ROLE_ASSIGNED_MENU on m.MENU_ID
equals ra.MENU_ID
join rp in db.TBL_IMS_USER_ROLE_PRIVILEGES on ra.UROLE_ID
equals rp.GRANTED_ROLE
where rp.USER_ID == UserID
group m by m.MENU_ID
into g select g).ToList();
if I used Var instead of List then how to fire loop?
I think you need to remove your join statements - and just use the where like you do in raw SQL query:
var qry = (from a in db.TBL_IMS_MENU
from b in db.TBL_IMS_ROLE_ASSIGNED_MENU
from c in db.TBL_IMS_USER_ROLE_PRIVILEGES
where c.USER_ID == UserID
where b.UROLE_ID == c.GRANTED_ROLE
where a.MENU_ID == b.MENU_ID
where a.menu_status == "Active"
where a.menu_master != "0"
select a)
.GroupBy(c => c.menu_id)
.ThenBy(c => c.menu_label)
.ThenBy(c => c.menu_value)
.ToList();
Try something like this:
var listSubMenu = (from m in db.TBL_IMS_MENU
join ra in db.TBL_IMS_ROLE_ASSIGNED_MENU on m.MENU_ID
equals ra.MENU_ID
join rp in db.TBL_IMS_USER_ROLE_PRIVILEGES on ra.UROLE_ID
equals rp.GRANTED_ROLE
where rp.USER_ID == UserID
group m by new { m.MENU_ID, m.menu_label, m.menu_value }
into g select g).ToList();
foreach(var groupItem in listSubMenu)
{
// go through groups like this - groupItem.Key.MENU_ID
foreach(var menuItem in grouItem)
{
//go through each item in group like this - menuItem.GRANTED_ROLE
}
}

LINQ to SQL get one-to-many table column result as array

I have one table[T1] with this informaions
ID
UserID
Other...
2nd table[T2] is
ID
UserID
Name
Relationship is one user from T1 can have many T2
I want to get result like
ID = number
UserID = number
array[t2.name,t2.name,t2.name]
My ling to sql is like
var result = (from t1 in context.t1
join t2 in context.UserID on t1.ID equals t2.UserID
select new CLASS
{
ID = t1.ID,
UserID = t1.UserID,
Names = t2.name
}).Take(10).ToList();
But this give me result as each t2.name as separated row. How i can gather all names in array?
LINQ to SQL , ASP.NET C# 4.0
I think something like this should work
var result = (from t1 in context.t1
join t2 in context.UserID on t1.ID equals t2.UserID
select new CLASS
{
ID = t1.ID,
UserID = t1.UserID,
Names = (from t2 in context.t2
select t2.Name
where t2.userID = t1.userID).toArray(),
}).Take(10).ToList();
hope it helps
You don't need to use the join. Create a relationship b/n your two linq entites in the linq designer and then you can run a query like this:
var q = from t in context.t1
select new { id = t1.id, names = t1.t2s.Select(t => t.Name).ToArray() };
You have to group your results by ID/UserID:
var result = (from t1 in context.t1
join t2 in context.UserID on t1.ID equals t2.UserID
group by new { t1.ID, t1.UserID } into g
select new CLASS
{
ID = g.Key.ID,
UserID = g.Key.UserID,
Names = g.ToArray()
}).Take(10).ToList();
However, when LINQ to SQL classes are prepared right that kind of queries can be made like:
var result = from t1 in context.t1 select new { id = t1.id, names = t1.t2s.ToArray() };

Resources