Select all columns instead of specifying columns in select new {} of Entity Framework Linq table join - entity-framework

I was trying to use left join, but an existing answer said make my life easier by using from + from + select new. That worked, but instead of specifying each column in select new{} can I just have all columns?
For example, from
var items = from a in context.Table1
from b in context.Table2.Where(x=> a.Column1 == b.Column1).DefaultIfEmpty()
select new
{
Column1 = a.Column1
Column2 = a.Column2
.....
Column10 = b.Column5
};
to something like
var items = from a in context.Table1
from b in context.Table2.Where(x=> a.Column1 == b.Column1).DefaultIfEmpty()
select all;

Related

Ordering data after an intersection Postgresql

I'm working on a db homework question. It asks that the data be in descending order. However, I'm using an intersection in my query because of the many to many relationship.
The schema for Genre is
CREATE TABLE Genre (
movie_id integer REFERENCES Movie(id),
genre GenreType,
primary key (movie_id,genre)
);
My code is currently
$genres = tokenise($argv[1], "&");
$i = 0;
$qry = "
(select m.title, m.YEAR, m.content_rating, m.lang, r.imdb_score, r.num_voted_users
from Movie m
join Rating r on (m.id = r.movie_id)
join Genre g on (m.id = g.movie_id)
where m.YEAR >= ".$startYear."
and m.YEAR <= ".$endYear."
and g.genre = '".$genres[$i]."')
";
$i++;
while ($i < count($genres)){
$qry = $qry."
intersect
(select m.title, m.YEAR, m.content_rating, m.lang, r.imdb_score, r.num_voted_users
from Movie m
join Rating r on (m.id = r.movie_id)
join Genre g on (m.id = g.movie_id)
where m.YEAR >= ".$startYear."
and m.YEAR <= ".$endYear."
and g.genre = '".$genres[$i]."')
";
$i++;
}
I'd like to order the final result with the statement
order by r.imdb_score desc, r.num_voted_users desc
However, tagging it onto the end of each select statement doesn't work (the output is still scrambled).
An intersect (or union or except) can only have a single ORDER BY at the end. Even if it "looks like" it belongs to the final query, it applies to the whole result, e.g.:
select m.title, m.YEAR, m.content_rating, m.lang, r.imdb_score, r.num_voted_users
from Movie m
join Rating r on m.id = r.movie_id
join Genre g on m.id = g.movie_id
where ...
intersect
select m.title, m.YEAR, m.content_rating, m.lang, r.imdb_score, r.num_voted_users
from Movie m
join Rating r on m.id = r.movie_id
join Genre g on m.id = g.movie_id
where ...
order by imdb_score desc, num_voted_users desc
Will sort the complete result of the intersect, note that you can't use a table alias when referencing the columns (and the column names correspond to the name from the first query).
Putting the individual queries between parentheses is not needed.
But the use of intersect seems strange to begin with.
It seems you are simulating a simple IN condition with that. As far as I can tell, you could replace that with a single query that uses where ... and genre in ('genre1', 'genre2', ....)
It will be easier to understand and it will also be a lot faster.
You can still do something like that :
SELECT *
FROM
(
[Your_Entire_Query_With_All_Your_Intersects]
) T
ORDER BY [Your_Conditions];
But I don't know exactly what you want to do. Your query seems quite odd to me. Why the intersect in the first place?

linq subquery join and group by

Hi is it possible to translate the below queries into linq ? ...
I am using entity frameworks core and tried to use the stored procedure but it seems like i have to create a model that applies to the metadata of the stored procedure. So i am trying to understand whether this kinda such query can be translated into linq so i don't have to create a separate db model.
SELECT
Stock.stockID ProductID,
stockName ProductName,
categoryName ProductCategory,
typeName ProductType,
sizeName ProductSize,
currentQuantity CurrentQuantity,
standardQuantity QuantityPerBox,
CONVERT(VARCHAR(255),CONVERT(INT,Stock.price)) AvgUnitCost,
CONVERT(VARCHAR(255),CONVERT(INT,x.lastUnitCost)) LastOrderUnitCost,
CONVERT(VARCHAR(10),CONVERT(DATE,x.lastOrderDate)) LastOrderDate
FROM dbo.Stock
LEFT JOIN
(
SELECT stockID,unitPrice lastUnitCost ,orderDate lastOrderDate, ROW_NUMBER() OVER (PARTITION BY stockID ORDER BY orderDate DESC) rn FROM dbo.SalesOrder
JOIN dbo.SalesOrderDetail ON SalesOrderDetail.salesOrderID = SalesOrder.salesOrderID
WHERE customerID = #customerID AND salesStatus = 'S'
) x ON x.stockID = Stock.stockID AND rn = 1
LEFT JOIN dbo.StockCategory ON StockCategory.stockCategoryID = Stock.stockCategoryID
LEFT JOIN dbo.StockType ON StockType.stockTypeID = Stock.stockTypeID
LEFT JOIN dbo.StockSize ON StockSize.stockSizeID = Stock.stockSizeID
WHERE disStock = 0
Almost everything is possible. you just need to be careful with performance.
var query =
from stock in db.Stocks
join x in (
from grp in (
from so in db.SalesOrders
join sod in db.SalesOrderDetails on so.SalesOrderId equals sod.SalesOrderId
where so.CustomerId == customerId && so.SalesStatus == "S"
orderby so.OrderDate descending
select new {
sod.StockId,
LastUnitCost = sod.UnitPrice,
LastOrderDate = so.OrderDate
} into inner
group inner by inner.StockId)
select grp.Take(1)) on x.StockId equals stock.StockId into lastStockSales
from x in lastStockSales.DefaultIfEmpty()
join sc in db.StockCategories on stock.StockCatergotyId equals sc.StockCategoryId into scLeft
from sc in scLeft.DefaultIfEmpty()
join st in db.StockTypes on stock.StockTypeId equals st.StockTypeId into stLeft
from st in stLeft.DefaultIfEmpty()
join ss in db.StockSizes on stock.StockSizeId equals ss.StockSizeId into ssLeft
from ss in ssLeft.DefaultIfEmpty()
where stock.DisStock == 0
select new MyDTO {
ProductId = stock.StockId,
ProductName = stock.StockName,
ProductType = st.TypeName,
ProductSize = ss.SizeName,
CurrentQuantity = stock.CurrentQuantity,
QuantityPerBox = stock.StandardQuantity,
AvgUnitCost = stock.Price,
LastOrderUnitCost = x.LastUnitCost,
LastOrderDate = x.LastOrderDate
};
As you can see is easy to rewrite these queries, I had to change a little bit the logic on how to get the latest sales for a stock item since ROW_NUMBER() OVER (PARTITION... is not supported from a LINQ perspective. Again, you would have to consider performance when rewriting queries.
Hope this helps.

Issues with the OR clause

I am having some trouble with the OR clause.
I am trying to join two large tables and given below is a sample data from the tables
Table1 (t1)
vendor addr1 city zip
ADT PO BOX 371956 PITSBURGH 15250
Table2 (t2)
vendor addr1 city zip
ADT PO Box 371956 Pittsburgh 15250-7956
The first two select statements given below display one row of data from the two tables.
In the third select, I have an OR clause and this does not display any rows.
The OR clause should not affect the result set.
select *
from t1
left join t2
on t1.addr1 = t2.addr1
select *
from t1
left join t2
on t1.addr1 = t2.addr1
and (t1.city = t2.city)
the select below does not display any data. WHY?
select *
from t1
left join t2
on t1.addr1 = t2.addr1
and ((t1.city = t2.city) or (t1.zip = t2.zip))
On your last query you have:
t1.addr1 = t2.addr2 AND
(
t1.city = t2.city OR
t1.zip = t2.zip
)
Considering your sample data:
t1."PO BOX 371956" = t2."PO Box 371956" AND -- TRUE
(
t1."PITSBURGH" = t2."Pittsburgh" OR -- FALSE
t1."15250" = t2."15250-7956" -- FALSE
)
You got:
= TRUE AND (FALSE OR FALSE)
= TRUE AND FALSE
= FALSE
So, no soup for you.

Linq to SQL self join where right part of join is filtered

I am trying to map a self join where the right table must be filtered, e.g. SQL such as this:
select t2.* from table t
left join table t2
on t2.parentID = t.ID and t2.active=1;
I can figure out the syntax if I wanted to filter the left table:
// works
var query = from t in table
where t.active= 1
join t2 in table
on t.parentID equals t2.ID into joined
from r in joined.DefaultIfEmpty() ...
But I can't figure out how to filter the right table. It seems like it should be something like this...
// does not work
var query = from t in table
join t2 in table
where t.field = 1
on t.parentID equals t2.ID into joined
from r in joined.DefaultIfEmpty() ...
(not valid... join can't have where). There is discussion of using multiple from clauses, but if I create more than one from clause, so I can add a where to the 2nd one, I can't figure out how to join the results of them into a new temporary table.
I can't just add a "where" after the join; the right table must be filtered first or matches will occur, and a where clause at the end would remove the row from the left table that I do want in the output. That is, the output should have rows where there's nothing matched from filtered right table. So I need to filter the right table before the join.
I think you are looking to do this:
var query = from t in table
join t2 in
(from t3 in table
where t3.field = 1
select t3)
on t.parentID equals t2.ID into joined
from r in joined.DefaultIfEmpty() ...
Another way is to use multiple from like this:
var query = from t in table
from t2 in table.Where(x => x.field = 1)
.Where(x => x.ID == t.parentID)
.DefaultIfEmpty()
select ....

INNER JOIN in EF 4

i have 2 tables master and details,
in EF 4 i want to write a query to retrieve a data like this t-sql
SELECT Table1.Table1ID, Table1.A, Table2.Table2ID, Table2.B
FROM Table1 INNER JOIN
Table2 ON Table1.Table1ID = Table2.Table1Id
i use this :
using(var context =new context())
{
var p = (from i in context.Table1.Include("Table2") select i);
}
but it returns rows in table1 how can i change it to retrieve rows in table2 and have my join?
thanks
I think you are looking for this:
var query = from a in context.Table1
join b in context.Table2 on a.Table1ID equals b.Table1Id
select new
{
a.Table1ID,
a.A,
b.Table2ID,
b.B,
};