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

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() };

Related

SQLite Foreign Key Relationship with Godot

This is the only way that I found to get the information from a foreign_key relationship. Is there a better way?
db.query("SELECT owner FROM dog_names;")
print(db.query_result)
print(db.query_result[0])
var o = db.query_result[0]["owner"]
print(o)
var o_str = "SELECT name FROM owners WHERE id = {int};"
var o_form = o_str.format({"int": o})
db.query(o_form)
print(db.query_result)
var query_str = "SELECT name FROM owners JOIN dogs ON owners.id = dogs.id;"
db.query(query_str)
print(db.query_result)
The below guide is from https://www.techonthenet.com/sqlite/joins.php
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

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();
}

Android Sqlite Multiple Joins with Alias does not return anything

I have this query:
Cursor res = db.rawQuery("SELECT t1.Id, t2.EmpId FROM table1 t1
LEFT JOIN table2 t2 ON t1.t2Id = t2.Id
LEFT JOIN table3 t3 ON t1.t3Id = t3.Id
WHERE t1.Id = 90909", null);
Now when I go
if(res.moveToFirst()){
do{
MyObject obj = new MyObject();
obj.Id = res.getInt(res.getColumnIndex("t1.Id"));
MyObjectAsProperty objProp = new MyObjectAsProperty();
objProp.EmpId = res.getInt(res.getColumnIndex("t2.EmpId"));
}while(res.moveToNext());
}
The objProp.EmpId returns nothing (or 0). I looked at the cursor columns and it's Fields basically did not include the table alias names. How do I go about getting the values of those aliased fields?
Thanks!
EDIT
Apologies. I forgot to add that if for example it's referencing the same other table multiple times with the same field.
Here's updated query
Cursor res = db.rawQuery("SELECT t1.Id, t2.EmpId, t2b.EmpId FROM table1 t1
LEFT JOIN table2 t2 ON t1.t2Id = t2.Id
LEFT JOIN table2 t2b ON t1.t2bId = t2b.Id
WHERE t1.Id = 90909", null);
if(res.moveToFirst()){
do{
MyObject obj = new MyObject();
obj.Id = res.getInt(res.getColumnIndex("t1.Id"));
MyObjectAsProperty objProp = new MyObjectAsProperty();
objProp.EmpId = res.getInt(res.getColumnIndex("t2.EmpId"));
MyObjectAsProperty objProp2 = new MyObjectAsProperty();
objProp2 .EmpId = res.getInt(res.getColumnIndex("t2bId.EmpId"));
}while(res.moveToNext());
}
The documentation says:
The name of a result column is the value of the "AS" clause for that column, if there is an AS clause. If there is no AS clause then the name of the column is unspecified and may change from one release of SQLite to the next.
So you must use AS:
SELECT t1.Id AS ObjID, t2.EmpId AS EmpId, ...

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
}
}

Count resulted records using linq to sql

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();

Resources