I have two data tables as following
TableA TableB
UID QID
QID Value1
Value2
I want to join two data tables and get Value1 and Value 2. I tried the following, but I am not getting any data back.
string str = "AAA";
var result = (from t1 in TableA.AsEnumerable()
//join between two tables
join t2 in TableB.AsEnumerable() on t1.Field<string>("UID") equals t2.Field<string>("QID")
//where conditions
where t2.Field<string>("QID") == str && t1.Field<string>("QID") == "ABCD"
//select clause
select t2.Field<string>("Value1"));
This is my query with out using LINQ and its working.
Select t2.Value1, t2.value2 from TableA t1 JOIN TableB t2 ON t2.QID = t1.UID WHERE t2.QID = 'AAAAA' AND t1.QID = 'XXXX'
Thanks for your help.
Your LINQ code should work, I guess you just need to use the same where the condition values for QID.
where t2.Field<string>("QID") == "AAA" && t1.Field<string>("QID") == "ABCD"
is not equal to your SQL:
WHERE t2.QID = 'AAAAA' AND t1.QID = 'XXXX'
It should work when you set correct values in LINQ
Related
I have two table as below
Table1
IntervalID(pK)
1
2
3
Table 2
IntervalID Name
1 XXX
Output should be (Table1+Table2)
IntervalID Name
1 XXX
2 NULL
3 NULL
I have done like below
Table1.Merge(Table2);
But it does not give desired output
You could achieve this by using Left join, like the following code:
var result = (from t1 in table1
join t2 in table2 on t1.IntervalId equals t2.IntervalId into leftedResults
from leftedResult in leftedResults.DefaultIfEmpty()
select new { t1.IntervalId, Name = leftedResult?.Name }).ToList();
Note that, you can't merge two DataTables that not have similar schemas.
Left join for DataTables :
var result = (from t1 in dataTable1.AsEnumerable()
join t2 in dataTable2.AsEnumerable() on t1.Field<int>("IntervalId") equals t2.Field<int>("IntervalId") into leftedResults
from leftedReult in leftedResults.DefaultIfEmpty()
select new { IntervalId = t1.Field<int>("IntervalId"), Name = leftedReult?.Field<string>("Name") }).ToList();
I hope you find this helpful.
I have a Linq query that is joining on 2 nullable properties.
var result = (from A in context.TableA
join B in context.TableB
on A.ExecutionId equals B.ExecutionId
where B.InsertedBy == userName
Both rep.ExecutionId and sch.ExecutionId are nullable int in the database. What I really want Entity Framework to generate is
select
column1
from TableA A
inner join TableB B on A.ExecutionId = B.ExecutionId
where B.InsertedBy = #username
but what I get is
select
column1
from TableA A
inner join TableB B on A.ExecutionId = B.ExecutionId
OR ((A.[ExecutionId] IS NULL) AND (B.[ExecutionId] IS NULL))
where B.InsertedBy = #username
(Neither one of the ExecutionIds are primary keys). The second query gives me WAY more records than what I need, but more importantly, is not the query that I want. How can I write the LINQ so that it produces the first query or an equivalent?
If you do not want any records where ExecutionID is null, then use a filter
var result = (from A in context.TableA.Where( a => a.ExecutionID != null )
join B in context.TableB.Where( b => b.ExecutionId != null )
on A.ExecutionId equals B.ExecutionId
where B.InsertedBy == userName
...`enter code here`
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
I have a LINQ query that I need to use a ternary operator on so certain joins are used based on certain criteria. So this is my query.
var lData = (from r in gServiceContext.CreateQuery("campaignresponse")
join a in gServiceContext.CreateQuery("activityparty") on ((EntityReference)r["activityid"]).Id equals ((EntityReference)a["activityid"]).Id
//tenary statement here
join c in gServiceContext.CreateQuery("contact") on ((EntityReference)a["partyid"]).Id equals c["contactid"]
where ((EntityReference)r["new_distributorid"]).Id.Equals(lProfileProperty.PropertyValue)
select new
{
});
This is what I want to do.
If r["new_distributorid"] == 1 I need to use:
join c in gServiceContext.CreateQuery("contact") on ((EntityReference)a["partyid"]).Id equals c["contactid"]
if r["new_distributorid"] == 2 then I need to use:
join c in gServiceContext.CreateQuery("account") on ((EntityReference)a["partyid"]).Id equals c["accountid"]
and if r["new_distributorid"] == 3 then I need to use:
join c in gServiceContext.CreateQuery("lead") on ((EntityReference)a["partyid"]).Id equals c["leadid"]
So basically is new_distributor == 1 I need to use a certain join if its a 2 I need another join and if its a 3 I need another join.
Is this possible? If it is, how would I go about setting that up?
Thanks!
All that's changing is a single string value, so just determine that string value before you start defining the query:
string tableName = "";
switch(r["new_distributorid"])
{
case(1):
tableName = "contact";
case(2):
tableName = "account";
case(3):
tableName = "lead";
}
string tableID = tableName + "id";
//...
join c in gServiceContext.CreateQuery(tableName)
on ((EntityReference)a["partyid"]).Id equals c[tableID]
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.