How to select different fields using .Concat for Union All query - linq

I’m doing some preliminary work getting data consumption ready from a webAPI controller in MVC. I’m using a linq query that mimics a union query that uses two joins. However, I need the select statement to ask for a different field on each side of the union. This works fine in SSMS when I run the query, but when I create the query in linq it will not allow the fields to be different. It gives an error saying that each anonymous type requires a receiver of the same type. This is referring to the two anonymous types created via select new { }… Here’s the two queries.
In SQL:
Select m.Last_Name, first_name, m.dc_number, Dept_Job as JobOrStatus FROM
Master_Roster m
INNER JOIN Class_Assignment a on m.dc_number = a.dc_number
where a.subject_am = 'y1'
AND Start_Date_AM <= '1/31/18'
UNION ALL
Select m.Last_Name, first_name, m.dc_number, status_am FROM Master_Roster m
INNER JOIN Attend_am_y1 at on m.dc_number = at.dc_number
where at.class_date_am >= '1/1/18'
AND at.class_date_am <= '1/31/18'
ORDER BY Last_Name
In linq:
(from m in db.Master_Roster
join c in db.Class_Assignment
on m.dc_number equals c.dc_number
orderby m.Last_Name
where c.Subject_AM == "y1"
select new { m.dc_number, m.Last_Name, m.First_Name }).Concat(
from m in db.Master_Roster
join a in db.attend_am_y1 on m.dc_number equals a.dc_number
orderby m.Last_Name
where a.class_date_am >= date1 &&
a.class_date_am <= date2
select new { m.dc_number, m.Last_Name, m.First_Name });
If I were to add dept_job and status_am to the linq query, it throws aforementioned error. I’d like to do this without using a stored procedure. Any ideas?

Instead of putting into 2 anonymous types, put into the same viewmodel and concat. Eg:
Internal Class ConcatViewModel{
public int DcNumber {get;set;}
public string LastName {get;set;)
// etc...
}
Then:
select new ConcatViewModel{
DcNumber = m.dc_number,
LastName = m.Last_Name,
FirstName = m.First_Name,
Status = m.Dept_Job
}
and
select new ConcatViewModel{
DcNumber = m.dc_number,
LastName = m.Last_Name,
FirstName = m.First_Name,
Status = m.status_am
}
(assuming that status_am and Dept_Job are the same underlying type)

Related

Linq Group by / Distinct with Join table

i plan to join 2 table, and get the distinct value of language column. How should i achieve that in Linq? I try add 'group' but no luck. Besides, i want to select s value too together with r distinct language value.
My code:
public ActionResult QuestionLink(int Survey_ID)
{
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group r.language << this is not work **
select r;
return PartialView(query.ToList());
}
This is what in MoreLinq is called DistinctBy. But if that method works on IEnumerable, so you can't use it in an EF query. But you can use the same approach:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new { r, s } by r.language into grp
select grp.FirstOrDefault();
But I wonder if this really is what you want. The result depends on the ordering of languages that the database happens to return. I think you should add a predicate for a specific language and remove the grouping:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
&& r.language == someVariable
select new { r, s };
You can do like this:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new {r, s} by r.language into rg
select rg.Key;

Entity Framework Query select hard-coded user created column

I'm creating a select from multiple tables using a union as I need to return a list of activities that has occurred for a particular client on the database. I need to return each union with an added column so I can tell the difference between the results. If I was to do the query in SQL it would look something like this:
SELECT cn.NoteID, cn.Note, cn.InsertedDate, 'Note Added' Notes
FROM Client c
INNER JOIN ClientNotes cn ON cn.ClientID = c.ID
WHERE c.ClientID = #ClientID
UNION
SELECT rc.ID, rc.CommNote, rc.InsertedDate, 'Communication Added' Notes
FROM ReceivedCommunication rc
LEFT JOIN Job j ON j.ID = rc.JobID
WHERE j.ClientID = #ClientID or rc.ClientID = #ClientID
My Question is how in Entity Framework using IQuerable do I return the hard-coded Notes column?
I have something like this so far:
Dim client as IQueryable(Of myresultclass) =
(From c As Client
Join cn As ClientNotes In ClientCompanyNotes On c.ID Equals cn.ClientID
Where c.ClientID = ClientID
Select cn.NoteID, cn.Note, cn.InsertedDate).Union(
From rc As ReceivedCommunication In ReceivedCommunications
Join j As Job In Jobs On j.ID Equals rc.JobID
Where j.ClientID = ClientID or rc.ClientID = ClientID
Select rc.ID, rc.CommNote, rc.InsertedDate)
Thanks for your help
Ok worked it out, should have been obvious. For anyone with the same issue, I had to update my Select from Select cn.NoteID, cn.Note, cn.InsertedDate to:
Select New myresultclass With {
.ActivityID = cn.NoteID,
.ActivityType = "Note Added"
.InsertedDate = cn.InsertedDate
}
for each one of the unions that I had
Thanks

Linq Nested Inner Joins

I want to join the following Tables
1. B_Book[1st Table]
-B_BID (Book ID)(PK)
-B_Name
-B_CategroyID (FK)
2. BI_BookInstance [2nd Table]
-BI_IID(Instance ID)
-BI_BID (FK)
-BI_Price
3. BC_BookCategory [3rd Table]
-BC_CategoryID (PK)
-BC_CategoryName
First Join B_Book and BI_BookInstance then join the result of those both with BookCategory.
(1st join)[B_BID equals BI_BID]
(2nd nested join)[result of 1st join B_CategoryID equals BC_CategoryID]
Edit
SQL would be something like the following:
SELECT * FROM
(SELECT * FROM B_Book b JOIN BI_BookInstance bi on b.B_BID = bi.BI_BID) as t1
JOIN BC_BookCategoryID bc on bc.BC_CategoryID = t1.B_CategoryID
What matches your query in LINQ would be the following (and you'll notice the similarity with SQL). I've also included some examples on how to rename the fields returned, such as Price or CategoryName:
var results = from b in B_Book
join bi in BI_BookInstance
on b.B_BID equals bi.BI_BID
join bc in BC_BookCategory
on b.B_CategoryID equals bc.BC_CategoryID
select new
{
// put in whatever fields you want returned here:
b.B_BID,
b.B_CategoryID,
b.B_Name,
bi.BI_BID,
bi.BI_IID,
Price = bi.BI_Price,
bc.BC_CategoryID,
CategoryName = bc.BC_CategoryName
};
I have supposed inner joins (your FKs is not null), so i would like query like this:
var ctx = new YourEntities();
var query = from b in ctx.B_Book
from bi in ctx.BI_BookInstance
from bc in ctx.BC_BookCategory
where b.B_BID == bi.BI_BID && b.B_CategoryID == bc.BC_CategoryID
select new
{
BInstID = bi.BI_IID,
BName = b.B_Name,
BPrice = bi.BI_Price,
BCategory = bc.BC_CategoryName
};
foreach (var item in query)
{
Console.WriteLine(item.BInstID);
Console.WriteLine(item.BName);
Console.WriteLine(item.BPrice);
Console.WriteLine(item.BCategory);
Console.WriteLine("");
}
You can do this without explicitly using linq's join statement, provided that navigation properties are in place:
from b in ctx.B_Book
from bi in b.BookInstances
select new { b.Property1, bi.Property2, b.BookCategory.Name }

Linq query with two joins on inner select in EF

I'm trying to create a Linq query for EF that joins on 2 values from an inner select. Underneath you will find the SQL query that does the trick, things are much more tricky when trying to do so in Linq.
I use POCO object and would like the query to return the List and not an anonymous type. Is this possible with Linq to EF?
SELECT s1.*
FROM [Statistics] s1
INNER JOIN
(
SELECT MAX(CreateDate) as createdate
FROM [Statistics]
GROUP BY UserId
) s2
ON s1.UserId = s2.[UserId] and s1.CreateDate = s2.createdate
ORDER BY s1.Balance desc
You can do this with a Where or a Join.
from s1 in Statistics
join s2 in (from s in Statistics group s by s.UserId into g
select new { UserId = g.Key, CreateDate = g.Max (s => s.CreateDate) })
on new { s1.UserId, s1.CreateDate } equals new { s2.UserId, s2.CreateDate }
orderby s1.Balance descending
select s1;
Or,
from s1 in Statistics
from s2 in (from s in Statistics group s by s.UserId into g
select new { UserId = g.Key, CreateDate = g.Max (s => s.CreateDate) })
where s1.UserId == s2.UserId && s1.CreateDate == s2.CreateDate
orderby s1.Balance descending
select s1;

Join statement in Linq to Sql

I need to write Join statment after writing query in linq
example :
var Query = (from Tab in Db.Employees
select Tab)
as i have some cases to perform join operation so
i need to do it on this Query Query.Join(Join with another Table like Department); I need the Syntax
if (DeptID != -1){ Query.Join(Join with table Department where FkDeptID = DeptID); }
Consider the usage of join in the LINQ 'query syntax':
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
Something like this?
var results = (from q in Query
join m in myList on q.SomeID = m.SomeID
select unknown);
Try using this query:
var Query =
from e in Db.Employees
join d in Db.Departments on e.FkDeptID equals d.DeptID into departments
select new
{
Employee = e,
Department = departments.SingleOrDefault(),
};
This works assuming that when e.FkDeptID == -1 that there is no record in the Departments table and in that case Department would be assigned null.
You should never have more than one department for an employee so I've used SingleOrDefault rather than FirstOrDefault.

Resources