Sub Query in LINQ - c#

I have an SQL Query as given below
SELECT ui.PageStyleCss
FROM UserImages ui
WHERE ui.UserImageId IN
( SELECT inv.UserImageId
FROM Invitation inv
JOIN InviteeEmails invEmails ON
inv.InviteID = invEmails.InviteID
WHERE invEmails.InviteGUID = #InviteGUID
)
How can I write this in LINQ?
Thanks

My wild guess is that you're using LINQ to SQL. It would be nice if you mentioned this, along with details of your model. Guessing at its structure...
var q = from ui in Context.UserImages
where ui.Invitations.Any(i => i.InviteeEmails.Any(e => e.InviteGuid = inviteGuid))
select ui.PageStyleCss;

from ui in db.UserImages
where (from inv in db.Invitations
join invEmails from InviteeEmails
on inv.InviteId equals invEmails.InviteId
where invEmails.InviteGUID == inviteGUID
select inv.UserImageId).Contains(ui.UserImageId)
select ui.PageStyleCss
(not sure if it compiles or not)
I have to assume there's a better way...this is pretty much a direct translation.

Related

Rewrite Entity Framework LINQ query into T-SQL

How can I rewrite the following Linq query into normal T-SQL?
var list = (from t in context.ParentTable
where t.ChildRecords.Count == t.ChildRecord.Count( c => c.BooleanColumn )
select t).ToList();
Thanks in advance...
Something like this, but you'll need to determine the relationship between the ParentTable and ChildRecord tables to make it work, I'm just guessing at the cr.ParentTableId = pt.ParentTableId part.
select pt.*
from ParentTable pt
where not exists
(select 1
from ChildRecord cr
where cr.ParentTableId = pt.ParentTableId
and cr.BooleanColumn = 0)
On a side note the Linq could be changed to the following instead.
var list = (from t in context.ParentTable
where t.ChildRecords.All(c => c.BooleanColumn)
select t).ToList();

Multiple table linq query?

Could you help me translate this SQL query in Linq and Lambda expression.
SELECT * FROM User
JOIN UserIdentifier ON User.id = UserIdentifier.user_fk
JOIN UserPassword ON User.id = UserPassword.user_fk
WHERE UserIdentifier.identifier_value = "key" AND UserPassword.password = "1234"
I already wrote this
var query = from u in context.Users
join ui in context.UserIdentifiers on u.id equals ui.user_fk into Joined
from j in Joined.DefaultIfEmpty()
join up in context.UserPasswords on u.id equals up.user_fk into Joined2
from ???
select new { id = u.id, identifier = j.identifier_value, password = Joined2.???}
with help of http://paragy.wordpress.com/2010/11/18/multiple-joins-with-linq-and-lambda/
I'm not a happy user of linq. Actually I don't like linq because of this kind of request. This one is simple but when you try complex request linq is a nightmare. It's even worst with dynamic request. I always have problem with linq syntax and the web doesn't really help. I don't find a correct documentation to write queries.
I guess I'm not the first one to ask this question but all the documentation I found seems wrong or doesn't help me. This is a simple query and I don't find correct help. I'm still waiting someone prove me that link is not just another POC.
You're missing a where clause.
And your SQL joins are regular INNER JOINs, so you don't need these join ... into g from x in g.DefaultIfEmpty() -> that's how you do an equivalent of LEFT OUTER JOIN.
var query = from u in context.Users
join ui in context.UserIdentifiers on u.id equals ui.user_fk
join up in context.UserPasswords on u.id equals up.user_fk
where ui.identifier_value == "key" && up.password == "1234"
select new
{
id = u.id,
identifier = ui.identifier_value,
password = up.password
};

How to create Linq to Sql with left join, aggregate, and where clause

Does anyone know how to convert this query to LINQ to SQL?
SELECT posts.*, count(COMMENTS.*) AS comment_count FROM POSTS
LEFT JOIN COMMENTS on POSTS.id = COMMENTS.post_id
WHERE comments.date IS NULL OR comments.date >= [NOW]
GROUP BY posts.id
ORDER BY comment_count DESC
It's simple enough in SQL, but I am having trouble wrapping my head around linq to sql. Any help would be appreciated!
Thanks
You want something like this:
var query =
from p in POSTS
join c in COMMENTS on p.id equals c.post_id into cs
group new
{
Post = p,
Comments = cs
.Where(c1 => c1.date >= DateTime.Now)
.Count(),
} by p.id;
just a suggestion you can always use this great tool
http://www.sqltolinq.com/
to help with conversion

Help Converting T-SQL to LINQ

Have the following (non-straightforward) T-SQL query, which i'm trying to convert to LINQ (to be used in a L2SQL expression):
declare #IdAddress int = 481887
select * from
(
select top 3 p.*
from tblProCon p
inner join vwAddressExpanded a
on p.IdPrimaryCity = a.IdPrimaryCity
where a.AddressType = 3
and p.IsPro = 1
and a.IdAddress = #IdAddress
order by AgreeCount desc
) as Pros
union
select * from
(
select top 3 p.*
from tblProCon p
inner join vwAddressExpanded a
on p.IdPrimaryCity = a.IdPrimaryCity
where a.AddressType = 3
and p.IsPro = 0
and a.IdAddress = #IdAddress
order by AgreeCount desc
) as Cons
order by ispro desc, AgreeCount desc
In a nutshell, i have an #IdAddress - and i'm trying to find the top 3 pro's and top 3 con's for that address.
The above query does work as expected. I'm not entirely sure how to convert it to a LINQ query (never done unions before with LINQ). I don't even know where to start. :)
Query-style/Lambda accepted (prefer query-style, for readability).
Also - i have LinqPad installed - but i'm not sure how to "convert T-SQL to Linq" - is there an option for that? Bonus upvote will be awarded for that. :)
The above T-SQL query performs well, and this L2SQL query will be executed frequently, so it needs to perform pretty well.
Appreciate the help.
var baseQuery = (from p in db.tblProCon
join a in db.vwAddresssExpanded
on p.IdPrimaryCity equals a.IdPrimaryCity
where a.AddressType == (byte) AddressType.PrimaryCity &&
a.IdAddress == idAddress
order by p.AgreeCount descending
select p);
var pros = baseQuery.Where(x=> x.IsPro).Take(3);
var cons = baseQuery.Where(x=> !x.IsPro).Take(3);
var results = pros
.Union(cons)
.OrderByDescending(x => x.IsPro)
.ThenByDescending(x => x.AgreeCount)
.ToList();
You can call (some query expression).Union(other query expression).
You can also (equivalently) write Enumerable.Union(some query expression, other query expression).
Note that both expressions must return the same type.
AFAIK, there are no tools that automatically convert SQL to LINQ.
(For non-trivial SQL, that's a non-trivial task)

linq to sql report tables in query

Here's the method i want to write:
public static IEnumerable<String> GetTableNames(this IQueryable<T> query)
{
//...
}
where the IQueryable is a linq-to-sql query (is there a more specific interface i should use?).
then if i had a query like this
var q = from c in db.Customers
from p in db.Products
from cp in db.CustomerProducts
where c.ID = 3 && cp.CustID == c.ID && p.ID == cp.ProdID
select new {p.Name, p.Version};
q.GetTableNames();// return ["Customers", "Products", "CustomerProducts"]
basically it would show all the tables that this query touches in the db, it is ok to execute the query to figure this out too (since that is going to happen anyway)? any ideas?
(EDIT: sorry if this is a little too "give me teh codez!", any tips, partial solutions, or explanations of why this is impossible will be considered Thanks! -Luke)
LINQ-to-SQL allows you to capture the TSQL easily - just set .Log. The problem then is parsing that. I would be tempted to capture the TSQL, and play it back in SSMS with SET STATISTICS IO ON - this gives easily parsed per-table results.
You could do DataContext.GetCommand(query).CommandText, then parse that looking for FROM and JOIN clauses (tricky would be cartesian (comma) joins).

Categories

Resources