How to return values from query when joining multiple tables in Linq? - linq

I have a Linq queries that have tables join and couple of tables inner join together. Sometimes I got an error from the query when table is empty. What I trying to do is I am tryting to get a value from table even if other table is empty.
Thanks in Advance.

You need to do left join
Assuming left join between customer and order table.
var query =
from customer in dc.Customers
from order
in dc.Orders
.Where(o => customer.CustomerId == o.CustomerId)
.DefaultIfEmpty()
select new { Customer = customer, Order = order }
Also refer below link
http://forums.asp.net/t/1792428.aspx/1

Related

Hibernate, Order by count of subquery on ManyToMany using Predicates

I have a query written using Predicates in Hibernate and I need to add a subquery on a join table to count the number of joins and order by the number of joins where they exist in an array of ids.
The join table is a ManyToMany relation.
I am using flyway to setup the table schema, so while the join table exists in the database, a join model is not needed in Hibernate to join the 2 related models therefore no join model exists.
I don't care about retrieving these related models, I just want the number of joins so that I can order by them.
The following is PostGreSQL, which works. I need to convert the following PSQL into a Predicate based query:
SELECT u.*, COUNT(jui.interest_id) AS juiCount
FROM "user" u
LEFT JOIN (
SELECT ui.user_id, ui.interest_id
FROM user_interest ui
WHERE ui.interest_id IN (?)
) AS jui ON u.id = jui.user_id
GROUP BY u.id
ORDER BY juiCount DESC
Where the ids provided for the IN condition are passed into the subquery. The above query is in PostGreSQL.
Working with what I have so far:
CriteriaBuilder b = em.getCriteriaBuilder();
CriteriaQuery<User> q = b.createQuery(User.class);
Root<User> u = q.from(User.class);
// This doesn't make sense because this is not a join table
// Subquery<Interest> sq = q.subquery(Interest.class)
// Root<Interest> squi = sq.from(Interest.class);
// sq.select(squi);
// sq.where(b.in("interest_id", new LiteralExpression<Long[]>((CriteriaBuilderImpl) b, interestIds)));
q.orderBy(
// b.desc(b.tuple(u, b.count(squi))),
b.asc(u.get(User_.id))
);
q.where(p);
return em
.createQuery(q)
.getResultList();
Everything I have managed to find doesn't quite seem to fit right given that they are not using ManyToMany in the use of q.subquery() in their example.
Anyone can help fill in the blanks on this please?

LINQ Equivalent of and SQL query with two inner joins and a left join

I would be grateful for help with a LINQ equivalent of the following SQL Query (which works). Below this SQL query I give some description of my simple data base and the problem I want to solve.
Select a.Name, a.OrderID,
b.ProductIDFirst, c1.productName ProductNameFirst,
b.ProductIDSecond , c2.productName ProductNameSecond
from Customers a
INNER JOIN ORDERS b ON a.OrderID = b.OrderID
left join products c1 on b.productidfirst = c1.productid
left join products c2 on b.ProductIDSecond = c2.productid
Background information on the database structure:
I have a simple SQL Server Database with three Tables named Products, Orders and Customers.
The business model is such that each order can have only two products (not more).
The Orders table has two foreign keys, though they both come from the Products table. These Foreign Key field Names in the Orders Table are ProductIDFirst and ProductIDSecond. These two Foreign Keys in the orders table correspond to two products that each order can have. Customers table has one Foreign Key which comes from the Orders Table.
Now I need help with an LINQ query that will return me all customers such that I get five fields - CustomerName, OrderID and Names of each of the two products that match the OrderID in the customer product.
Your links are non-existent, so here's a best attempt without seeing anything.
Assuming you have the following containers (you'll need to change them for your scenario):
var customers = new List<Customer>();
var orders = new List<Order>();
var products = new List<Product>();
You can do the following:
var query =
from a in customers
join b in orders
on a.OrderId equals b.OrderId
join c1 in products
on b.ProductIdFirst equals c1.ProductId into c1a
join c2 in products
on b.ProductIdSecond equals c2.ProductId into c2a
from p1 in c1a.DefaultIfEmpty()
from p2 in c2a.DefaultIfEmpty()
select new
{
Name = a.Name,
OrderId = a.OrderId,
ProductIdFirst = p1 == null ? null : p1.ProductIdFirst,
ProductNameFirst = p1 == null ? null : p1.ProductNameFirst,
ProductIdSecond = p2 == null ? null : p1.ProductIdSecond,
ProductNameSecond = p2 == null ? null : p1.ProductNameSecond,
};
In short, where you want a left join, project the join into something else (e.g. c1a, c2a) then call from on them using DefaultIfEmpty() which will set null when no matching item exists on the right-hand-side.

Select All columns for all tables in join + linq join

How to select all columns from tables in join using linq
Sql:
select CTRL_RUN_JOB.*, CTRL_DATA_STREAM.*
from CTRL_RUN_JOB inner join CTRL_DATA_STREAM
on CTRL_RUN_JOB.DATA_STREAM_ID= CTRL_DATA_STREAM.DATA_STREAM_ID
Linq:
from CTLJCRJOB in CTRL_RUN_JOBs
join CTLRFDSTM in CTRL_DATA_STREAMs
on CTLJCRJOB.DATA_STREAM_ID equals CTLRFDSTM.DATA_STREAM_ID
select new {
CTLJCRJOB.* // ???
,CTLRFDSTM.* // ???
}
Thanks
While you cant expand them to columns, you can simply return the entities. Eg:
select new { CTLJCRJOB, CTLRFDSTM }
If you need it flattened, then you will have to write out the mapping yourself, but will still be very trivial.
You could use the into clause, but it will not flatten it for you.
from CTLJCRJOB in CTRL_RUN_JOBs
join CTLRFDSTM in CTRL_DATA_STREAMs
on CTLJCRJOB.DATA_STREAM_ID equals CTLRFDSTM.DATA_STREAM_ID into ALLCOLUMNS
from entry in ALLCOLUMNS
select entry
Another twist is
OutPutList = (from CTLJCRJOB in CTRL_RUN_JOBs
join CTLRFDSTM in CTRL_DATA_STREAMs
on CTLJCRJOB.DATA_STREAM_ID equals CTLRFDSTM.DATA_STREAM_ID
select CTLJCRJOB).ToList();
You could use the into clause, but it will not flatten it for you.
from CTLJCRJOB in CTRL_RUN_JOBs
join CTLRFDSTM in CTRL_DATA_STREAMs
on CTLJCRJOB.DATA_STREAM_ID equals
CTLRFDSTM.DATA_STREAM_ID into ALLCOLUMNS
from entry in ALLCOLUMNS
select entry
in this way we can only get CTLJCRJOB columns result, there was no CTLRFDSTM table columns through my test

LINQ - join , group by (multiple fields), group by, select new some fields

i need select some fields from a table in the query using join, but in the select new statement i dont have acess from the fields of the join table.
var query = from p in persistencia.RequisicaoCompraItems
join s in persistencia.Suprimentos on p.SuprimentoID equals s.SuprimentoID
(i need get fields from this join)
group p by new {p.SuprimentoID, p.RequisicaoCompraItemID, p.RequisicaoCompraID } into x
from res in x
orderby x.Key.SuprimentoID
select new {res.SuprimentoID ,
res.RequisicaoCompraItemID,
**but in here i cant acess** };
Cheers**
They're in res.Key.SuprimentoID etc

Linq To Entity Framework selecting whole tables

I have the following Linq statement:
(from order in Orders.AsEnumerable()
join component in Components.AsEnumerable()
on order.ORDER_ID equals component.ORDER_ID
join detail in Detailss.AsEnumerable()
on component.RESULT_ID equals detail.RESULT_ID
where orderRestrict.ORDER_MNEMONIC == "MyOrderText"
select new
{
Mnemonic = detail.TEST_MNEMONIC,
OrderID = component.ORDER_ID,
SeqNumber = component.SEQ_NUM
}).ToList()
I expect this to put out the following query:
select *
from Orders ord (NoLock)
join Component comp (NoLock)
on ord .ORDER_ID = comp.ORDER_ID
join Details detail (NoLock)
on comp.RESULT_TEST_NUM = detail .RESULT_TEST_NUM
where res.ORDER_MNEMONIC = 'MyOrderText'
but instead I get 3 seperate queries that select all rows from the tables. I am guessing that Linq is then filtering the values because I do get the correct values in the end.
The problem is that it takes WAY WAY too long because it is pulling down all the rows from all three tables.
Any ideas how I can fix that?
Remove the .AsEnumerable()s from the query as these are preventing the entire query being evaluated on the server.

Resources