Left join and case clause LINQ in Entity Framework - c#

I am needing to make a left join and also use the select operator case.
My LINQ basic is this and works:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao
});
But I must add a new field and it should be formatted, then my LINQ looked like this:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = a.Horario.ToString("yyyy-MM-dd HH:mm:ss")
}
);
This error happens:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
If you add the ToList() or AsEnumerable() in db.AgendaHorario.ToList() and db.Agenda.ToList() and db.Profissional.ToList() error that appears is:
Object reference not set to an instance of an object.
What should I do to have a left join with case and fields and formatted fields

Try this:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = a.Horario
}).AsEnumerable().Select(x => new
{
id = x.id,
Medico = x.Medico,
start = x.start.ToString("yyyy-MM-dd HH:mm:ss")
}
);

try to set the string in a variable then assign it to your query like this:
var myValue = Horario.ToString("yyyy-MM-dd HH:mm:ss");
resultado.Dados = (
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = myValue
} );

Related

Sql Join Subquery output in Linq

I'm write some SQL query with join and sub query i want convert into linq
select a.CampaignId, a.ImagePath,(select Count(a1.CampaignId) from INN_Customers_Campaigns_Images a1 where a1.CampaignId = a.CampaignId)ImageCount from INN_Customers_Campaigns_Images a
inner join INN_Customers_Gallary b On b.CampaignId = a.CampaignId and a.CreatedBy = b.CustomerId
You can use let clause for your sub query
var result = from a in context.INN_Customers_Campaigns_Images
join b in context.INN_Customers_Gallary on new { a.CampaignId , a.CreatedBy } equals new { b.CampaignId , b.CustomerId }
let imageCount = context.INN_Customers_Campaigns_Images.Where(a1 => a1.CampaignId == a.CampaignId).Count()
select new
{
a.CampaignId,
a.ImagePath
ImageCount = imageCount
}

MVC Invalid length parameter passed to the LEFT or SUBSTRING function

I have a SQL command wherein I am trying to join multiple columns in a single table which is,
dbo.tbl_Application AS APP on (APP.motor_no = SUBSTRING(R.remarks, CHARINDEX('|', R.remarks) + 1, LEN(R.remarks))) AND (Year(APP.date_created) = YEAR(R.txndate)) AND (APP.motor_no = M.motor_no)
Now I converted it to Linq
CONVERTED TO LINQ
join APP in db.tbl_Application on new
{ motor_no = R.remarks.Substring(5), R.txndate.Value.Year, motor_no2 = M.motor_no }
equals new
{ motor_no = APP.motor_no, APP.date_created.Value.Year, motor_no2 = APP.motor_no }
And then added to my existing linq which is:
EXISTING LINQ
from R in db.vwEtracs_Receipt
join RI in db.vwEtracs_ReceiptItem on new { parentid = R.objid } equals new { parentid = RI.parentid }
join IA in db.vwEtracs_IncomeAccount on new { objid = RI.acctid } equals new { objid = IA.objid }
join M in db.vwQVFS_Motor on new { motor_no = R.remarks.Substring(5) } equals new { motor_no = M.motor_no } into M_join
from M in M_join.DefaultIfEmpty()
join OOI in db.vwQVFS_OOI on new { operator_id = R.payerId } equals new { operator_id = OOI.operator_id } into OOI_join
from OOI in OOI_join.DefaultIfEmpty()
join CR in db.vwQVFS_COR on M.motor_id equals CR.motor_id into CR_join
from CR in CR_join.DefaultIfEmpty()
join F in db.vwQVFS_Franchise on new { or_id = R.objid } equals new { or_id = F.or_id } into F_join
from F in F_join.DefaultIfEmpty()
join T in db.vwQVFS_TODA on M.toda_id equals T.toda_id into T_join
from T in T_join.DefaultIfEmpty()
join RT in db.vwQVFS_RT on new { payer_id = R.payerId } equals new { payer_id = RT.payer_id } into RT_join
from RT in RT_join.DefaultIfEmpty()
join B in db.vwQVFS_Brand on M.brand_id equals B.brand_id into B_join
from B in B_join.DefaultIfEmpty()
If I include the line of code from above, I am getting the error Invalid length parameter passed to the LEFT or SUBSTRING function. but if I remove it, my Linq works perfectly.
What is making causing this error? Thanks in advance.
You getting the error because there is at least one record shorter than 5 characters in your database db.vwEtracs_Receipt.remarks column. So in your SQL, you don't pass length actually but in your linq you use Substring(int length). So the substring length can't be longer than the actual string length

multiple join clause ended with a group join LINQ

I working on an app with a SQLite database, now I want to select information from multiple tables using linq, here it is what I did:
from c in dataContext.Convention
join e in dataContext.Engineer on c.Engineer equals e.Code
join o in dataContext.Owner on c.Owner equals o.Code
join t in dataContext.ProjectType on c.ProjectType equals t.Id
join cs in dataContext.ConventionState on c.State equals cs.Id
join sc in dataContext.SiteControl on c.Code equals sc.CodeCv
join pc in dataContext.PlanControl on c.Code equals pc.CodeCv
join scs in dataContext.SiteState on sc.State equals scs.Id
join pcs in dataContext.PlanState on pc.State equals pcs.Id
join rcs in dataContext.ReceptionState on sc.Reception equals rcs.Id
join b in dataContext.Bill on c.Code equals b.CodeCv
where cs.Abr == "EC"
group new { c, e, o, t, scs, pcs, rcs, b } by new
{ c.Code, c.NumSeq, c.Year, c.TotalAmount, c.Title, e.LastName, e.FirstName, o.Name,
tprjt = t.Abr,
scState = scs.Abr,
pcState = pcs.Abr,
rcState = rcs.Abr
} into cvgrp
select new
{
Code = cvgrp.Key.Code,
N_Seq = cvgrp.Key.NumSeq,
Exercice = cvgrp.Key.Year,
Intitulé = cvgrp.Key.Title,
Ingenieur = cvgrp.Key.LastName + " " + cvgrp.Key.FirstName,
MaitreOuvrage = cvgrp.Key.Name,
TypeProjet = cvgrp.Key.tprjt,
CtrlPlan = cvgrp.Key.pcState,
CtrlChantier = cvgrp.Key.scState,
Reception = cvgrp.Key.rcState,
Montant = cvgrp.Key.TotalAmount,
MontantFacturé = cvgrp.Sum(x => x.b.Amount),
MontantRestant = cvgrp.Key.TotalAmount - cvgrp.Sum(x => x.b.Amount),
MontantCréance = cvgrp.Sum(x => x.b.IsPaid == "False" ? x.b.Amount : 0.0 )
}
It seems working but I really don't understand clearly what I did especially in the group by clause. If I add an into clause after the joins before the group by the identifier will work as a table with all the tables joined ?.
I need some explanation to understand linq more.
Thank you in advance.

Check whether object NOT exists in another table in LINQ?

I have a query in entity framework which gets some messages from tables.
var ur = (from m in en.Messages
join mb in en.aspnet_Membership on m.FromUserId equals mb.UserId
join urs in en.UserProfiles on mb.UserId equals urs.UserId
join g in en.Groups on m.ToUserId equals g.GroupId
join ug in en.UserInGroups on g.GroupId equals ug.GroupId
where ug.UserId == userId
select new
{
InboxId = m.MessageId,
FromUser = urs.RaveName.Trim(),
CreatedOn = m.CreatedOn
}
).Concat(
// msg is not deleted
from m in en.Messages
join mb in en.aspnet_Membership on m.FromUserId equals mb.UserId
join urs in en.UserProfiles on mb.UserId equals urs.UserId
where m.ToUserId == userId
select new
{
InboxId = m.MessageId
,
FromUser = urs.RaveName.Trim()
,
CreatedOn = m.CreatedOn
}
);
I have another table which shows whether the message is used:
var msg = (from m in en.MessagesUsed
where m.UserId == userId
select m
);
Now, I need to check: Is there a message in 'ur' that is not in 'msg'? In T-SQL, we can use:
SELECT 1
FROM ur
WHERE NOT EXISTS (SELECT 1 FROM msg WHERE msg.Id = ur.InboxId AND msg.FromUser = ur.FromUser AND msg.CreatedOn = ur.CreatedOn)
to check this. But how to do it in LINQ?
Thanks

Linq query with a Conditional WHERE Clause

I am new to LINQ so apologises upfront
I have the following Linq query :-
var OrdersByBranches =
from a in AllOrders
join b in AllBranchKeys
on a.BranchKey equals b.BranchKey
orderby a.Date
group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
select new
{
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a =>
a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};
I need to include a where clause in the above query ... only if a variable called
BranchKeySelected is ""
I have tried using an If Else statement and have the same above query duplicated with
one containing a where clause and one NOT. ...But When I do this .. then OrdersByBranches
is NOT available outside of the IF Statement
Would be grateful for any help
Regards
Ghost
var OrdersByBranches =
from a in AllOrders
join b in AllBranchKeys on a.BranchKey equals b.BranchKey
orderby a.Date
group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
select new {
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a => a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};
if(string.IsNullOrEmpty(BranchKeySelected ))
{
OrdersByBranches = OrdersByBranches.Where(/*blbabla*/);
}
return OrdersByBranches;
Try (and my linq is not polished)
var OrdersByBranches = from a in AllOrders
join b in AllBranchKeys on a.BranchKey equals b.BranchKey
where b.BranchKeySelected.Contains("")
orderby a.Date group a by new
{
a.Date,
a.paymentMethod
}
into BranchOrderGrouped
select new
{
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a => a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};

Categories

Resources