OrdersRepository ordersRepository = new OrdersRepository();
var productInQuery = ordersRepository.ProductIn;
var orderInfoQuery = ordersRepository.OrderInfo;
var result = (from p in productInQuery
from o in orderInfoQuery
where p.refNo == o.refNo
select new {
t1 = p.no,
t2 = o.no}).ToArray();
I wrote like above code for inner join. and I want to add some conditional statement for OrderInfo context.
...
if(orderDate != DateTime.MinValue){
orderInfoQuery = orderInfoQuery.Where(x => x.orderDate == orderDate);
}
// also I tried this too. no is integer in Mysql and I'm sure there is 222 value.
// but still it return always null...
orderInfoQuery = orderInfoQuery.Where(x => x.no == 222);
var result = (from p in productInQuery
from o in orderInfoQuery
where p.refNo == o.refNo
select new {
t1 = p.no,
t2 = o.no}).ToArray();
I add the conditional statement but it return always null. (I check DB(Mysql) value is existed)
And is it not inner join?
var result = (from p in productInQuery
join o in orderInfoQuery on p.refNo equals o.refNo
select new {
t1 = p.no,
t2 = o.no}).ToArray();
Any body know this, please advice me~
Thank you!
[EDIT]
OMG, I'm so sorry, the productIn and orderInfo is never matched. that's why it return always null.
May I ask question again please,
var result = (from p in productInQuery
join o in orderInfoQuery on p.refNo equals o.refNo
join x in productQuery on p.productNo equals x.no
join t in productOutQuery on p.no equals t.productInNo into productIn
from t in productIn.DefaultIfEmpty()
orderby o.processDate descending
select new
{
qty = p.qty,
dateIn = o.processDate,
dateOut = (DateTime?)(from m in orderInfoQuery where m.refNo == t.refNo select m.processDate).FirstOrDefault(),
etaDate = (DateTime?)(from w in orderInfoQuery where w.refNo == t.refNo select w.eta).FirstOrDefault(),
}).ToArray();
this is my linq code, and I want to search by etaDate now.
how can I write linq code. In above code, the etaDate is just sub query. and I want to get
the date that etaDate is exactly matched with specific date.
could you help me please?
Thank you!
You might want to make sure that the types between the two dates here:
orderDate != DateTime.MinValue
and here:
x.orderDate == orderDate
are in the same date format. If one value has a different format or adds extra precision, then the conditional will always fail.
Related
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();
}
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, ...
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
}
}
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();
var result = (from p in productInQuery
join o in orderInfoQuery on p.refNo equals o.refNo
join x in productQuery on p.productNo equals x.no
join t in productOutQuery on p.no equals t.productInNo into productIn
from t in productIn.DefaultIfEmpty()
//let dateOut = (from m in orderInfoQuery where m.refNo == t.refNo select m.delivered).FirstOrDefault()
orderby o.processDate descending
select new
{
modelNo = x.modelNo,
mfgNo = p.mfgNo,
serialNo = p.serialNo,
poNo = p.poNo,
lbs = p.lbs,
width = p.width,
height = p.height,
depth = p.depth,
qty = p.qty,
dateIn = o.processDate,
dateOut = (DateTime?)(from m in orderInfoQuery where m.refNo == t.refNo select m.processDate).FirstOrDefault()
}).ToArray();
I want to add this result into iTextSharp table cell.
but I don't know how to do,
I tried,
int resultSize = result.Length;
/*
for (int j = 0; j < resultSize; j++)
{
table.AddCell(result[j]);
}
*/
foreach (string[] test in result) //Error : Unable to cast object of type
{
int testSize = test.Length;
for (int j = 0; j < testSize; j++)
{
table.AddCell(test[j]);
}
}
but I lost way :(
anybody knows, please advice me~
[EDIT]
int resultSize = result.Length; //192
test does have a fields...
[EDIT 2]
Actually the result be returned from Model.
PJ.WebUI.Models Reports Class
public class Reports
{
public Array GetTransaction(){
OrdersRepository ordersRepository = new OrdersRepository();
var productInQuery = ordersRepository.ProductIn;
var productOutQuery = ordersRepository.ProductOut;
var productQuery = ordersRepository.Product;
var orderInfoQuery = ordersRepository.OrderInfo;
var result = (from p in productInQuery
join o in orderInfoQuery on p.refNo equals o.refNo
join x in productQuery on p.productNo equals x.no
join t in productOutQuery on p.no equals t.productInNo into productIn
from t in productIn.DefaultIfEmpty()
//let dateOut = (from m in orderInfoQuery where m.refNo == t.refNo select m.delivered).FirstOrDefault()
orderby o.processDate descending
select new
{
modelNo = x.modelNo,
mfgNo = p.mfgNo,
serialNo = p.serialNo,
poNo = p.poNo,
lbs = p.lbs,
width = p.width,
height = p.height,
depth = p.depth,
qty = p.qty,
dateIn = o.processDate,
dateOut = (DateTime?)(from m in orderInfoQuery where m.refNo == t.refNo select m.processDate).FirstOrDefault()
}).ToArray();
return result;
}
}
And in controller call the method to get the result.
Reports reposrts = new Reports();
var result = reposrts.GetTransaction();
..
foreach (var test in result)
{
table.AddCell(test.modelNo);
}
Then
Error 1 'object' does not contain a definition for 'modelNo' and no extension method 'modelNo' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
So,
I move the model method into controller method (put all together in same method) and run. then it works!.
but the result be used in the other controller too. so I want to keep the result in Model class to reuse.
I want to know why it does not work if the result query is not in same method.
could you help me a little more please?
Thank you very much!
'result' will be an array of the anonymous type you selected to, not an array of string arrays, which is why you are getting an error in the foreach loop.
Your loop should probably look more like the following:
foreach (var test in result)
{
table.AddCell(test.modelNo);
table.AddCell(test.mfgNo);
table.AddCell(test.serialNo);
// etc
}
#Edit 2:
Because the result of GetTransaction() is 'Array', the calling method has no idea what the type is, it just sees it as an array of objects, and, because it is an anonymous type, you can't (reasonably) cast it back to the expected type.
I think your best bet in this case would be to make a new class which has the properties you want to return, e.g.:
public class Transaction
{
public string ModelNo { get; set; }
public string MfgNo { get; set; }
public string SerialNo { get; set; }
// etc. - but with the correct types for the properties
}
Then change the linq query to select into this type, instead of the anonymous type, e.g.:
...
orderby o.processDate descending
select new Transaction
{
ModelNo = x.modelNo,
MfgNo = p.mfgNo,
SerialNo = p.serialNo,
// etc.
...
And change the return type of GetTransaction() from Array to Transaction[].
It's not clear what you are trying to do but I believe you are casting each element of your result as a string incorrectly.
Try this:
foreach (var test in result)
You will probably need to tweak your inner code since test isn't an array, but that should get you past your current error.