Need help converting this joined table TSQL statement to Linq - c#

I looked at some of the other related questions, but didn't find a good answer. My TSQL query works fine:
SELECT POR.ReqNum ,
POR.ReqLine ,
XF.* -- Expand this..
FROM E10DB.Erp.PORel POR
INNER JOIN E10DB.Erp.ReqDetail RD ON RD.ReqNum = POR.ReqNum
INNER JOIN E10DB.Ice.XFileAttch XF ON XF.Key1 = CONVERT(NVARCHAR(50),
RD.ReqNum)
WHERE POR.PONum = #ponum
AND RD.Company = #company
AND XF.Company = #company;
I would like to translate this into a LINQ result like:
var joinResultRows = from PORel , etc.,...........
so I can do loop through them to do something :
foreach(var joinResult in joinResultRows)
{
string custID = joinResult.CustID;
string ponum = joinResult.PONum;
}
Any thoughts? Thanks!

Related

Cannot make 5 consecutive "joins" in LINQ?

I have this rather complex query in SQL server 2008:
declare #LanguageID as int = 1
select k.datePublish, k.dateEditing, k.dateTables
from TableAreasLevel1 as areaL1
inner join TableAreasLevel2 as areaL2
on areaL1.LanguageID = areaL2.LanguageID and
areaL1.CodeAreaLevel1 = areaL2.CodeAreaLevel1
inner join TableAreasLink as link
on areaL2.CodeAreaLevel1 = link.CodeAreaLevel1 and
areaL2.CodeAreaLevel2 = link.CodeAreaLevel2 and
inner join TableProducts as tblProds
on tblProds.CodeAreaLevel1 = areaL1.CodeAreaLevel1 and
tblProds.CodeAreaLevel2 = areaL2.CodeAreaLevel2
inner join TableSI_Products as prod
on prod.SiAreaCode = link.SiAreaCode
inner join TableCalendar as k
on k.KodTableSI_Products = tblProds.KodTableSI_Products
where areaL1.LanguageID = #LanguageID and
prod.Code = 'some string' and
k.LanguageID = #LanguageID and
tblProds.LanguageID = #LanguageID;
I am trying to develop the same query in LINQ, but I get error when I try join the table TableProducts, i.e the third consecutive join.
Here is my LINQ query:
List<Tuple<DateTime, DateTime, DateTime>> dates = (from areaL1 in gpe.TableAreasLevel1
join areaL2 in gpe.TableAreasLevel2
on new { areaL1.CodeAreaLevel1, areaL1.LanguageID } equals
new { areaL2.CodeAreaLevel1, areaL2.LanguageID }
join link in gpe.TableAreasLink
on new { areaL2.CodeAreaLevel1, areaL2.CodeAreaLevel2, areaL2.RbrOblastNivo2} equals
new {link.CodeAreaLevel1, link.CodeAreaLevel2}
join tblProds in gpe.TableProducts
on tblProds. // The name tblProds is not in the scope of the left side of 'equals'
);
Is the problem connected with how the tables are designed or, something else I should check for?
Any ideas, why tblProds is not visible in the scope of the LINQ query?
You are using Query as your guide something like:
on k.KodTableSI_Products = tblProds.KodTableSI_Products
but take a look at your linq:
on new { areaL1.CodeAreaLevel1, areaL1.LanguageID } equals
it has two fields. I think its not a good idea.
linq join something like
var dates = (from areaL1 in gpe.TableAreasLevel1
join areaL2 in gpe.TableAreasLevel2
on areaL1.PKFields equals areaL2.PKFields
where areaL1.CodeAreaLevel1== areaL2.CodeAreaLevel1 && areaL1.LanguageID = areaL2.LanguageID
Select new YournewClass{YournewClass.Field1=areaL1.fields1, And so on}
)
You can do to join the other tables with aliases.
Sorry need to go for now.
I'm giving you an idea.
Hope it helps.

linq2sql - How to use raw SQL to get a count from DB?

Currently, for a getting a count of items in a complicated query with joins i am doing something like this --
string q = #"SELECT f.FILE_ID
FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
WHERE l.EntityId = 123";
var files = Context.ExecuteQuery<File>(q);
return files.Count();
any better way to do this, rather than getting all the ID's back and counting?
I would prefer to do a SELECT Count(*) and get the int back in linq.
Instead of returning FILE_ID collection you can return the ready COUNT as a part of your SQL query:
string q = #"SELECT COUNT(f.FILE_ID)
FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
WHERE l.EntityId = 123";
return Context.ExecuteQuery<Int32>(q);
try this
string q = #"SELECT COUNT(f.FILE_ID)
FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
WHERE l.EntityId = 123";
return Context.ExecuteQuery<Int32>(q).FirstOrDefault();

Linq to SQL: Sum with multiple columns select

I want to convert the following SQL code into linq to sql but can't seem to find a way
select holder_name,agent_code,sum(total)
from agent_commission
group by agent_code
Can anyone help me? Am kinda stuck with this for quite a while.
Thanks in advance
UPDATE:
I tried the following
var query = (from p in context.Agent_Commissions
group p by new
{
p.agent_code
}
into s
select new
{
amount = s.Sum(q => q.total),
}
);
How do I select the other two columns? What am I missing?
In fact your SQL query works only when the corresponding relationship between holder_name and agent_code is 1-1, otherwise the Group by agent_code won't work. So your linq query should be like this:
var query = from p in context.Agent_Commissions
group p by p.agent_code into s
select new {
holder_name = s.FirstOrDefault().holder_name,
agent_code = s.Key,
amount = s.Sum(q => q.total)
};
Here is your linq query
from a in ctx.agent_code
group a by a.holder_name, a.code into totals
select { holder_name = a.holder_name,
code = a.code,
total = totals.Sum(t=>t.total)}
Given that you have linq2sql context in ctx variable and it has your table in it.

NHibernate Criteria engine with inner join and subquery

Is it posible in NHibernate to create a query that looks like this?
select hi.ContactId
From dbo.vw_HostInterests hi INNER JOIN
( Select cm1.ContactId
From dbo.vw_ContactMoments cm1 INNER JOIN
(
Select Contactid
From dbo.vw_ProfileNaw
where GenderId = 1000
) as pn1 on cm1.ContactId = pn1.ContactId
where cm1.ActivityId = 1001
)as cm on hi.ContactId = cm.ContactId
where hi.ActivityId = 1038
I've managed to create the correct output with the IN statement, but I'd realy like the SQL to look like this.
The Criteria below shows part of above query with the IN Statement I used (but want to replace):
ICriteria criteria = DbSession.CreateCriteria<Contact>();
var dCriteria1 = DetachedCriteria.For(typeof(VwHostInterest))
.Add(Expression.Eq("ActivityId", 1038))
.SetProjection(Projections.ProjectionList()
.Add(Projections.GroupProperty("ContactId")));
var dCriteria2 = DetachedCriteria.For(typeof(VwContactMoment))
.Add(Expression.Eq("ActivityId", 1001))
.SetProjection(Projections.ProjectionList()
.Add(Projections.GroupProperty("ContactId")));
criteria.Add(Subqueries.PropertyIn("ContactId", dCriteria1));
criteria.Add(Subqueries.PropertyIn("ContactId", dCriteria2));
int count = (Int32)criteria
.SetProjection(Projections.Count("ContactId"))
.UniqueResult();
Probably not the answer you are looking for and apologies if it isn't but my experience is that your best bet with such complex queries would be to:
a) Do this whole thing as a view and map it in NHibernate
b) Create the inner select as a view and create a mapping such that you can relate it in your query
b) Or override nhibernate (override as in skip and not in OO terms ;) and write this as a named query using native SQL.
Does that nested query produce the same result as the following?
SELECT hi.ContactId
FROM dbo.vw_HostInterests hi
INNER JOIN vw_ContactMoments cm1 on hi.ContactId = cm1.ContactId
AND cm1.ActivityId = 1001
INNER JOIN dbo.vw_ProfileNaw pn1 on pn1.ContactId = cm1.ContactId
AND pn1.GenderId = 1000
WHERE hi.ActivityId = 1038

How to compare List<String> to DB Table using LINQ

I have a list<> of phone numbers and I am trying to join that with the corresponding records in the db table and get an order number and a customer ID. Also the list has the whole number as one string and the DB has it broken to area code, prefix, number each as separate fields.
I am fairly new to LINQ, so this is a beyond what I currently know. Any suggestions are GREATLY appreciated.
var tnbrs = new List<string>();
have tried:
var tntable = tnbrs.Cast<DataSet>();
var tntable = tnbrs.AsQueryble();<code>
var custdata = from c in db.CUSTs
join t in tntable on c.NPA + c.NXX + c.LINE_NBR equals t.???
select new { c.PON, c.PartnerID };
You dont have to cast tnbrs to dataset
try this instead
var custdata = from c in db.CUSTs
where tnbrs.Contains(c.NPA + c.NXX + c.LINE_NBR)
select new { c.PON, c.PartnerID };
It generates sql query something like this
SELECT [t0].[PON], [t0].[PartnerID]
FROM [dbo].[CUSTs ] AS [t0]
WHERE [t0].[NPA]) + [t0].[Nxx] + [t0].[LINE_NBR] IN (#p0, #p1)

Categories