convert sql to linq sample - sql

I've got a sql statement, but I can't get it working in linq. Can someone show me how I can write the following sql statement as linq?
SELECT * FROM mobileApplication
LEFT JOIN videoMobile ON mobileApplication.id = videoMobile.mobileApplicationId
AND videoMobile.videoId = 257
It's a left join with a where statement on the right table. It works in sql server 2005, but I'd like to write it in linq.

I didn't verify the syntax, but try this...
var mobileApplications = from ma in mobileApplication
join vm in videoMobile on ma.id equals vm.mobileApplicationId into j1
from j2 in j1.DefaultIfEmpty()
where vm.videoId == 257
select ma;

There is a product that will do this for you. I have found it very useful. The product name is Linqer. It is not free, but not expensive, and offers a 30 day trial. I have found very few queries it is not able to convert. It has worked well for me.
http://www.sqltolinq.com/

Its something like:
from ma in mobiledApplication.DefaultIfEmpty()
join vm in videoMobile on new { mobileApplicationId = ma.id, videoId = 257 } equals new { mobileApplicationId = vm.mobileApplicationId, videoId = vm.videoId } into videoMobileApplication
from vma in videoMobileApplication
select vma
The keys being the default if empty and using anonymous objects on the join criteria to incorporate 257 into the join.
I am pretty sure that using a where clause for the 257 will achieve the same result though...

Try some like this:
var query =
from m in mobileApplication
join v in videoMobile
on m.id = v.mobileApplicationId and v.id = 257
select m;
See here:
http://msdn.microsoft.com/en-us/library/bb397676%28v=VS.100%29.aspx
http://msdn.microsoft.com/en-us/magazine/cc163400.aspx

Related

Query on other query linq

Just assume a simple example:I have two table and use this query:
select *
from People
where PersonGuid = (select PersonGuid from Sellers where Guid = '')
How can I write this query with linq?
I tried this:
var person = from p in loginContext.Person where p.PersonGuid =
(loginContext.Seller.Where(s => s.Guid == sellerGuid).FirstOrDefaultAsync());
but that's wrong.
What is the right way to write it?
If you were to rewrite your SQL query as
select *
from People AS PE
JOIN
Sellers AS Sellers
ON PE.PersonGuid = SE.PersonGuid
WHERE
SE.Guid = ''
then the LINQ becomes a little more obvious:
var person = (from p in loginContext.Person
join s in loginContext.Seller on p.PersonGuid equals s.PersonGuid
where s.guid == ""
select p)
.FirstOrDefault();
Although your SQL would suggest FirstOrDefault is not required.
Warning - not tested.
You could probably try using LINQ JOIN clause.
It should be something like:
from p in loginContext.Person
join s in loginContext.Seller on new { p.PersonGuid = s.Guid }
where s.Guid = sellerGuid
You can know more about LINQ JOIN here -> Microsoft C# Reference
Hope it helps!
I will assume that select PersonGuid from Sellers where Guid = '' will provide a single value no matter what, otherwise your SQL statement would fail.
Accepted answer works, but if you want a solution that keeps the spirit of the SQL query, you can rely on Any function. Something along the following:
var person = await loginContext.Person
.Where(p => loginContext.Sellers
.Any(s => s.PersonGuid == p.PersonGuid && s.Guid = ""))
.FirstOrDefaultAsync();
I expect this to be transformed into an SELECT ... WHERE EXISTS which is similar to your initial query.

How to write sub query using linq in mvc5?

I am writing my sub query using linq in my application. I wrote my sql sub-query in sql server. When I execute this query in SQL Server the result give perfect and the sql query will be like
My SQL Server:
select Row_Number() Over(OrderBy Mmname) as Sno,Mmname,Mmcardno,Mmdob,MmEmail,(Select SUM(MSSRNETAMT) from MSCAS where MSCAS.MSSFORMNO = MSMEM.MmCardno and MSCAS.MSSRBILLDT between '01/01/2016' and '30/12/2016') Billopen,(Select SUM(MSSRNETAMT) from MSCAS where MSCAS.MSSFORMNO = MSMEM.MmCardno and MSCAS.MSSRBILLDT between '01/01/2016' and '30/12/2016') BillForm,Mmredpv,Msdval,Mmcontact,Mmdate,Mmaddr,MmCuser,MmCuserdt,Mmusercd,
Mmuser,Mmuserdt,Cast(Mmcntrn as int ) as Mmcntr from MSMEM inner join MSSCHEDET on MSMEM.Mschuid = MSSCHEDET.MSDID
My linq query
Var query = (from Ms in db.msmems join Mss in db. Msschedet on Ms. Mechuid equals mss. MSDID select new
{
name = Ms. Mmname,
Billopen = (from mc in db. MSCAS where Ms. Mmcardno = mc. Mssformno) select mc.MSSRNETAMT);
}):
This only I tried but I am getting error in bill open it is amount in that I am getting error
This is my SQL query. I tried to convert this sql query in linq. But I am failed many times, I got an error.
Could you try something like this? Without understanding your table structure better, I took a shot at optimizing this. Is there no reason that you couldn't do a second join to your MSCAS table?
var query = (from Ms in db.msmems
join Mss in db.Msschedet on Ms.Mechuid equals mss.MSDID
join Mc in db.MSCAS on Ms.Mmcardno equals Mc.Mssformno
select new {
name = Ms.Mmname,
Billopen = Mc.where(x=>x.MSSRBILLDT >= '01-01-2016' and x.MSSRBILLDT <= '12-30-2016').Sum(z=>z.MSSRNETAMT)
}
);

Convert this Query to Entity Framework LINQ

Can someone help me convert this SQL Query to EntityFramework LINQ. I don't know how to do Inner Join in EF.
select * from UserActivities INNER JOIN LoginHistories
ON UserActivities.iLoginHistoryId = LoginHistories.iLoginHistoryId
AND iUserId = 15
It is just a rough estimate (not enough context):
var db = GetDbContextSomehow();
var query = from ua in db.UserActivities
join lh in db.LoginHistories on ua.iLoginHistoryId equals lh.iLoginHistoryId
where ua.iUserId == 15
select ua;

Using LinQ with group by more than one column

I'm Newbi in LinQ, I have problem with group by in linQ.
I wan to query like this:
select
MAX(TCheckpointGrouping.Id) AS CheckpointGroupingId,
MAX(TCheckpointGrouping.MCheckpointId) AS CheckpointId,
MAX(MCheckpoint.Name) AS CheckpointName,
MAX(CAST(MCheckpoint.IsMajor AS VARCHAR)) AS IsMajor,
MAX(TCheckpointGrouping.MIndicatorId) AS IndicatorId,
MAX(MIndicator.Name) AS IndicatorName,
MAX(MCriteria.Id) AS CriteriaId,
MAX(MCriteria.Name) AS CriteriaName,
MAX(MPrinciple.Id) AS PrincipleId,
MAX(MPrinciple.Name) AS PrincipleName,
MAX(TCheckpointGrouping.RelationToCheckPoint) AS RelationToCheckPoint
from TCheckpointGrouping
inner join MCheckpoint on MCheckpoint.Id = TCheckpointGrouping.MCheckpointId
inner join MIndicator on MIndicator.Id = TCheckpointGrouping.MIndicatorId
inner join MCriteria on MCriteria.Id = MIndicator.MCriteriaId
inner join MPrinciple on MPrinciple.Id = MCriteria.MPrincipleId
group by
TCheckpointGrouping.MCheckpointId,
TCheckpointGrouping.MIndicatorId
How can i convert query above into LinQ (VB.NET)
thanks
bestRegards
I'm tempted to convert this SQL query to LINQ for you, but I think that would be a waste of opportunity for you to learn yourself.
There's a great page from Microsoft with lot of VB.NET Linq situations: 101 Linq Samples.
You can even find an example of a Group By using Multiple Columns.
Good learning. :)
I am not sure about this, but you can try it. In select part i have not included all the columns.
var result= from TChkgp in TCheckpointGrouping
join MCpoint in MCheckpoint on TChkgp.Id equals MCpoint.Id
join MIndtor in MIndicator on TChkgp.MIndicatorId equals MIndtor.Id
join MCrteia in MCriteria on MIndtor.Id equals MIndtor.MCriteriaId
join MPrncple in MPrinciple on MCrteia.MPrincipleId equals MPrncple.Id
group TChkgp by new (TChkgp.MCheckpointId,TChkgp.MIndicatorId} into g
select new {
CheckpointGroupingId =TChkgp.Id.Max(),
CheckpointId =TChkgp.MCheckpointId.Max,
....
....
};
you can see one simple example on following link
Group and sum in linq

Spatial Join in Entity Framework

I want to write a join statement in LINQ using the dbgeography's "Intersects" method (I am using EF June 2011 CTP). The problem is if I write something like this:
var joinQuery = from spQ in spatialTableQuery
join mnQ in MainQuery
on spQ.Polygon.Intersects(mnQ.PointGeography) equals 1
I get the following error:
The name 'mnQ' is not in scope on the left side of 'equals'. Consider
swapping the expressions on either side of 'equals'.
In SQL I have written a similar query as below so I know SQL suppports it:
SELECT * FROM Address a
INNER JOIN SPATIALTABLE b
WITH(INDEX(geog_sidx))
ON b.geom.STIntersects(a.PointGeography) = 1
Try something like this:
var joinQuery =
from spQ in spatialTableQuery
from mnQ in MainQuery
where spQ.Polygon.Intersects(mnQ.PointGeography) = 1