Retrieving Data From Multiple Tables in a LINQ to SQL query - c#

I'm new to LINQ and I'm not sure how to retrieve data from multiple tables from my SQL server database, here's the query:
SELECT cp.*, tsd.Action, tsd.CurrencyPair
from TradeStatsData tsd, CalculatedPrices cp
where tsd.TradeID = cp.TradeID and cp.Price is null and cp.ActiveTime < GETDATE()
The database uses the variable connection
How can I do this?

Your sql query would be something like this in LINQ:
var result = from tsd in TradeStatsData
join cp in CalculatedPrices on tsd.TradeID equals cp.TradeID
where cp.Price == null && cp.ActiveTime < DateTime.Now
select new
{
CP = cp,
Action = tsd.Action,
CurrencyPair = tsd.CurrencyPair
};

Linq is very similar to sql, just a little backwards.
from tsd in TradeStatsData
join cp in CalculatedPrices on tsd.TradeID equals cp.TradeID
where cp.Price == null && cp.ActiveTime < DateTime.Now
select new { cp.Col1... cp.ColN, tsp.Action, tsp.CurrencyPair }

Related

SQL to Linq/Lambda

Anyone can help me how to convert sql statement to linq and lambda like this ?
SELECT
tbl_terms.ID,
tbl_terms.Terms
FROM
tbl_terms
LEFT JOIN tbl_asn_uploaddoc ON tbl_terms.ID != tbl_asn_uploaddoc.Id_term
WHERE
tbl_asn_uploaddoc.Nip = '201948274838491943' && tbl_asn_uploaddoc.STATUS = 1
Thanks in advance
LINQ is mostly similar to SQL if you use query syntax instead of method syntax. Here is what I could gather quickly. Can't test because I don't have your model classes.
var Result = from t in context.tbl_terms
join d in context.tbl_asn_uploaddoc on t.ID != d.Id_term
where d.Nip = '201948274838491943' && d.STATUS = 1
select t.ID, t.Terms
Use below query that will give you LEFT JOIN on both of your entity,
var result = (from t in _con.tbl_Terms
join u in _con.tbl_asn_uploaddocs on t.ID equals u.Id_term
into tu
where !tu.Any()
from u in tu.DefaultIfEmpty()
where u.Nip == "201948274838491943" && u.STATUS == 1
select new
{
ID = t.ID,
Terms = t.Terms
}).ToList();
Where _con is your context.
You can use SQL to LINQ converter tool Linqer
Linqer is a SQL to LINQ conversion tool. It helps learning LINQ and convert existing SQL statements.

Use subquery in linq query

How can I construct the below sql query in linq query to get the results ?
SELECT PageNumber from LMS_SurveyQuestion WHERE SurveyQuestionID IN
(SELECT SurveyQuestionID from LMS_SurveyQuestionOptionChoice
WHERE NextPageNumber = 4) and SurveyID = 1
Have a look at this article. Basically, if you want to implement SQL IN query in LINQ, you need to construct an inner query first, and then use the Contains() method. Here's my attempt:
var innerQuery = (from log in LMS_SurveyQuestionOptionChoice where log.NextPageNumber = 4 select log.SurveyQuestionID);
var result = (from f in LMS_SurveyQuestion where innerQuery.Contains(f.SurveyQuestionID) && f.SurveyID = 1 select f);
Hope this will help.
try this
var result = from l in LMS_SurveyQuestion
let lsq = from l_S in LMS_SurveyQuestionOptionChoice
where l_S.NextPageNumber = 4
select l_S.SurveyQuestionID
where lsq.Contains(l.SurveyQuestionID) and l.surveyid = 1
select l.PageNumber;

Using SQL instead of LINQ in Telerik Open Access

I'm using Telerik Open Access. I have two separate projects that have Open Access data and then a third project that has the bulk of my code. I've been working on a way to convert a simple (at least I thought it was) SQL query to LINQ so that I can get the data I need. I have not been successful. I've had to break a single LINQ query into separate queries, because of the need for the Trim() function (I think). This has led to a lengthy piece of code and I'm still not getting the same results as my SQL query.
So my question is, is there anyway to use SQL instead of LINQ to access the data in the Open Access projects? If so, can you show me the syntax to do that for my query?
If it is not possible to use SQL, can you show me show me the proper way to convert my SQL query into LINQ so that I get the same results?
Thank you.
My SQL query is
SELECT DISTINCT us2.ccustno, us2.dispname, us2.csiteno, so.s1_name
FROM [DALubeDeacom].[dbo].[dmbill] bi
INNER JOIN [DALubeDeacom].[dbo].[dmso1] so
ON bi.bi_s1id = so.s1_id
INNER JOIN [DALubeNew].[dbo].[usersecurity] us2
ON so.s1_name = us2.cparentno
WHERE
us2.ctype = 'JOBSITE'
AND us2.csiteno is not null
AND us2.csiteno != ''
AND bi.bi_smid = '22'
ORDER BY us2.csiteno
My LINQ query is
public List<DataModelSample> GetLocationsBySalesNo(string salesNo)
{
int iSalesNo = int.Parse(salesNo.Trim());
try
{
var dmso = (
from so in deacom.Dmso1
join qt in deacom.Dmbills
on so.S1_id equals qt.Bi_s1id
where qt.Bi_smid == iSalesNo
select new Dmso1
{
S1_id = so.S1_id
, S1_name = so.S1_name.Trim()
}
);
var usec = (
from us in dbContext.Usersecurities
where us.Cparentno != null && us.Cparentno.Trim() != "" && us.Ctype.Trim() == "JOBSITE" && us.Csiteno.Trim() != ""
select new Usersecurity
{
Ccustno = us.Ccustno.Trim(),
Csiteno = us.Csiteno.Trim(),
Dispname = us.Dispname.Trim(),
Cparentno = us.Cparentno.Trim()
}
);
var customers =
(
from us in usec
join so in dmso
on us.Cparentno equals so.S1_name
select us
);
customers = customers.GroupBy(x => x.Csiteno).Select(x => x.First());
List<DataModelSample> listLocations =
(
from c in customers
select new DataModelSample
{
customerID = c.Ccustno
,
origLocationName = c.Csiteno + " " + c.Dispname
,
origLocationID = c.Csiteno
}
).OrderBy(x => x.origLocationID).ToList();
return listLocations.ToList();
}
catch (Exception ex)
{
throw ex;
}
} // GetLocationsBySalesNo(userInfo.csalesno)
Edit 1 - 2-19-16
Tried a suggestion by ViktorZ. His query was similar to the one I first tried. It returned the error "Identifier 'Ctype' is not a parameter or variable or field of 'DALube_DeacomModel.Dmbill'. If 'Ctype' is a property please add the FieldAlias or Storage attribute to it or declare it as a field's alias." From an online search, it looked like this was do to "extended fields". I don't seemed to be using such fields. The only way I could get around this error was to break it into the smaller LINQ queries in my original question, which didn't produce the right results. Any suggestions?
Here's the code:
var query = (from bill in deacom.Dmbills
join so in deacom.Dmso1 on bill.Bi_s1id equals so.S1_id
join us in dbContext.Usersecurities on so.S1_name equals us.Cparentno
where us.Ctype == "JOBSITE"
&& us.Csiteno != null
&& us.Csiteno != string.Empty
&& bill.Bi_smid == iSalesNo
select new
{
ccustno = us.Ccustno.Trim(),
dispname = us.Dispname.Trim(),
csiteno = us.Csiteno.Trim(),
s1_name = so.S1_name.Trim()
}).Distinct();
One very crude approximation of your SQL query is:
var query = (from bill in deacom.Bills
join so in deacom.LubeDeacom on bill.bi_s1id equals so.s1_id
join us in deacom.UserSecurity on so.s1_name equals us.cparentno
where us.ctype = "JOBSITE"
&& us.csiteno != null
&& us.csiteno != string.Empty
&& bill.smid = '22'
order by us.csiteno
select new
{
us.ccustno.Trim(),
us.dispname.Trim(),
us.csiteno.Trim(),
so.s1_name.Trim()
}).Distinct();
// to check the translation result
string sql = query.ToString()
// to get the results
var result = query.ToList()
If this is not working for you, you can always fall back to Telerik Data Access ADO.NET API. Here is a documentation article how to use it.

How do I convert this tSQL statement to LINQ using group by in a sub query

I have the following MSSQL query I am trying to convert to LINQ. I am using entity framework with the following syntax to get at the data.
var rv = (from i in DC.TableA select i).ToList();
This is the sql I want to write a C# LINQ query for but I cannot figure it out. Can someone help?
select BTO.*
from TableA BTO
join
(
select eqnum, max(testdate) as testdate
from TableA BTO1
where
BTO1.eqnum in ('M0435', 'Z0843') and
BTO1.testdate <= '2008-06-01'
group by eqnum
) T1
on
T1.eqnum = BTO.eqnum and
T1.testdate = BTO.testdate
order by EqNum;
I think there is opportunity to rewrite your query, but for information purposes I rewrote your sql into linq verbatim.
If you explain what you are trying to achieve we can provide alternative sql / linq
var eqnums = new[] { "M0435", "Z0843" };
var testdate = "2008-06-01";
var query = from bto in DC.TableA
join t1 in (
from bto1 in DC.TableA
where eqnums.Contains(bto1.eqnum) &&
bto1.testdate.CompareTo(testdate) <= 0
group bto1 by bto1.eqnum into g
select new
{
eqnum = g.Key,
testdate = g.Max(x => x.testdate)
}
) on new { bto.eqnum, bto.testdate } equals new { t1.eqnum, t1.testdate }
orderby bto.eqnum
select bto;

LINQ To DataSet from SQL

I am having trouble converting a SQL Join statement into LINQ to DataSet. Also, consider that there will be other tables in the LINQ statement that the Header table will be joined to. Below is my Join statement - any help is appreciated.
FROM Header
LEFT JOIN Address
ON Header.Customer = Address.Customer
AND Header.Company = Address.Company
AND ((Header.ShipTo = 'TEMP' AND Header.DocNum = Address.ShipTo)
OR Header.ShipTo <> 'TEMP' AND Header.ShipTo = Address.ShipTo)
Doing a join in Linq uses the Equals() method. When using multiple columns, you'll have to create an identically structured anonymous type for comparison.
from h in db.header
join a in db.address
on new {
cust = h.Customer,
comp = h.Company
}
equals new
{
cust = a.Customer,
comp = a.Company
}
where ((h.ShipTo == "TEMP" && h.DocNum == a.ShipTo)
|| h.ShipTo != "TEMP" && h.ShipTo == a.ShipTo)
select h;

Categories