I am trying to execute the following SQL statement using linq:
SELECT TTT.SomeField
FROM Table1 as T, Table2 as TT, Table3 as TTT
WHERE (T.NumberID = 100 OR T.NumberID = 101)
AND T.QuestionID = 200
AND T.ResponseID = TT.ResponseID
AND TT.AnswerID = TTT.AnswerID
Essentially getting one field from a third table based on primary/foreign key relationships to the other 2 tables. It is expected to have a single result every time.
var query = from t in db.Table1
join tt in db.Table2 on t.ResponseID equals tt.ResponseID
join ttt in db.Table3 on tt.AnswerID equals ttt.AnswerID
where (t.NumberID == 100 || t.NumberID == 101) && t.QuestionID == 200
select ttt.SomeField
If you always expect single result, you can wrap this in ().Single(), or, if there might be no results found, in ().SingleOrDefault().
If I understand you correct. You should read something about Joins I guess.
here
Related
I have an linq query like this :
var query = from Romm in RoMM
join rfrsa in RoMmfrsa on Romm.RoMmid equals rfrsa.RoMmid
join frsa in Frsa on rfrsa.Frsaid equals frsa.Fraid
join fra in Fra on frsa.Fraid equals fra.Fraid
where Romm.ActTypeId == 2 && Romm.SegmentId == 4
select new
{
Romm.ActTypeId,
Romm.RoMmid,
frsa.Fraid,
frsa.Frsaid,
Romm.ImpactId
};
And I have SQL code as below :
SELECT romm.ROMMID
, frsa.FRAID
, frsa.FRSAID
, romm.ImpactID
FROM RoMM AS romm
INNER
JOIN RoMMFRSA AS rfrsa
ON romm.RoMMID = rfrsa.RoMMID
INNER
JOIN FRSA AS frsa
ON rfrsa.frsaid = frsa.frsaid
INNER
JOIN FRA AS fra
ON frsa.FRAID = fra.FRAID
WHERE romm.acttypeid = 2
AND romm.segmentid = 4
The SQL only shows one row (which is correct), the linq shows the correct row and then it displays about another 3 rows which is not what we need. I need the linq to show one row which is correct with the SQL. Is this because of maybe many-many relationships ?
Looks like a typo in either the C# or the SQL join:
SQL: ON rfrsa.frsaid = frsa.frsaid
C#: rfrsa.Frsaid equals frsa.Fraid
^^^^^^
mismatch here
i am new to LINQ and joins, so Please forgive me if I am asking it wrong.
I have two tables
Table1
id name date
1 Mike 20-10-15
2 John 21-10-15
3 Sam 23-10-15
Table2
id name date
1 Ashle 19-10-15
2 Lily 21-10-15
3 Jeni 22-10-15
4 April 23-10-15
I need 5 records using Joins and should be orderby Date, most recent records.
Can you guys help me, I really need to figure out how Joins works with orderby.
Thanks
EDIT:
They are two different tables so no foreign key, so I think I can't use Join, so so far what I have done is like this
var combinddata = (from t1 in db.Table1
select t1.id)
.Concat(from t2 in db.Table2
select t2.id);
I don't know how to get only 5 records how to compare records from both tables on DateTime base.
Output should be
Sam
April
Jeni
John
Lily
You can concatenate equal anonymous types from different tables. If you also select the dates, you can sort by them, in descending order, and take the first 5 records:
Table1.Select (t1 =>
new
{
Id = t1.Id,
Name = t1.Name,
Date = t1.Date
}
).Concat(
Table2.Select (t2 =>
new
{
Id = t2.Id,
Name = t2.Name,
Date = t2.Date
}
))
.OrderByDescending (x => x.Date).Take(5)
Note that this gives precedence to items in Table1. If item 5 and 6 in the concatenated result are on the same date, but from Table1 and Table2, respectively, you only get the item from Table1.
If you want, you can select only the names from this result, but I assume that your output only shows the intended order of record, not the exact expected result.
var query =
from Table1 in table1
join Table2 in table2 on table1.id equals table2.id
orderby table1.date ascending
select table1.date;
Try this way
var combinddata = (from t1 in db.Table1
select t1.Name)
.Concat(from t2 in db.Table2
select t2.Name).OrderByDescending(x => x.date).Take(5);
I have a query that's something like this.
Select a.*
from table1 a
inner join table2 b on a.field1 = b.field1
inner join table3 c on b.field2 = c.field2
where b.field4 = beta and c.field5 = gamma.
On LINQ, I tried to do that this way:
var query = (from a in table1
join b in table2 on a["field1"] equals b["field1"]
join c in table3 on b["field2"] equals c["field2"]
where (b["field4"] == beta && c["field5"] == gamma)
select a).ToList();
But for some reason, when I try to do this I get an error that says that the entity "table2" doesn't have the field Name = "field5", as though as the where clause was all about the last joined table and the other ones were unaccessible. Furthermore, the compiler doesn't seem to notice neither, because it lets me write c["field5"] == gamma with no warning.
Any ideas? Am I writing this wrong?
Thanks
See these links:
How to: Perform Inner Joins (C# Programming Guide)
What is the syntax for an inner join in linq to sql?
Why you don't create View in database, and Select your data from View in LINQ?
I am trying to convert a ASP.NET project to Entity framework. How to re-write the following query to its LINQ equivalent?
SELECT {Table1 objects}
FROM [Table1] tb1
INNER JOIN [Table2] tb2
ON tb1.Table1ID = tb2.fk_Table1ID
WHERE tb2.fk_attrib1 = '123' AND tb2.fk_attrb2 = '345'
ORDER BY tb1.attrib1
The result is a collection of Table1 objects.
Here Table1 and Table2 correspond to object System.Data.Objects.ObjectSet of ADO.NET Entity Framework.
var results = from tb1 in Context.Table1
join tb2 in Context.Table2 on tb1.Table1ID == tb2.fk_Table1ID
where tb2.fk_attrib1 == "123" && tb2.fk_attrb2 == "345"
orderby tb1.attrib1
select tb1;
Something like this:
context.Table1
.Where( o => o.Table2s.Any( o2 =>
o2.fk_attrib1 == '123' &&
o2.fk_attrib2 == '345' ) )
.OrderBy( o => o.attrib1 )
.ToList();
BTW, LINQPad is great for trying out L2E queries.
This should help you a little bit. I suppose the main problem is with JOIN clause - in EF you can use NavigationProperties and don't need to worry about joining tables - EF will take care of that for you.
Also you are trying to filter on column from joined table. This you can do using Any method to find all Table1 elements that are connected to Table2 where those referenced elements have certain properties/columns. You should also get familiar with All method, as it might be useful to you in future.
from t1 in context.Table1
where t1.Table2s.Any(t2.fk_attrib1 == "123" && t2 => t2.fk_attrb2 == "345")
order by t1.attrib1
select t1;
Edit:
I assume that there is 1:n relationship between Table1 and Table2 which results in enumerable collection as NavigationProperty in Table1 objects.
Edit2:
Fixed error in code - didn't noticed that both attributes are from Table2 not Table1
Should be something like this:
var result = (from tb1 in Table1
from tb2 in Table2
where tb1.Key == tb2.Key &&
tb2.fk_attrib1 = '123' &&
tb2.fk_attrb2 = '345'
select ione).OrderBy(p=>p.attrib1);
Hope this helps.
Actually I think I might have fixed it, gonna do some testing, I wll post my solution if it works.
I am migrating an older DB system over to LINQ, I'm having trouble converting a few of the SQL statements though:
SELECT * FROM cities
INNER JOIN deals ON cities.cityId = deals.CityID
INNER JOIN countries ON cities.countryID = countries.CountryId
WHERE deals.endDate >= (someDate)
AND countries.CountryId = (1)
AND deals.soldout = (false)
I've done some research, but I can't get it to work. Here is the LINQ statement I came up with:
var deals = from d in db.deals
join city in db.cities on d.CityID equals city.cityId
join country in db.countries on city.countryID equals country.CountryId
where d.endDate > DateTime.Today && country.CountryId == 1 && d.soldOut == false
select d;
Is there some particular way to use 2 joins in LINQ?
Sorry, I had a formatting error: the statement is meant to select all the deals that have a city who's countryID = 1
You do not need the 2nd join if you have a country code for the city...
var deals = from d in db.deals
join city in db.cities on d.CityID equals city.cityId
where d.endDate > DateTime.Today &&
city.CountryId == 1 && d.soldOut == false
select d;
If you want columns from all tables involved, you can use an anonymous type for that.
select new {d, city, country}