SQL Server to Linq with a distinct and inner joins - c#

I'm trying to get this query to work but I just can't. I'm quite new to entity and linq. Thanks
select distinct
Usuario.idUsuario,
Usuario.Nombre,
Usuario.DNI
from
Usuario
right join
Relaciones on (Usuario.idUsuario = Relaciones.idUsuario)
inner join
Cursos on (Relaciones.idCurso = Cursos.idCurso)
This is what I tried so far
var query = from Usuario in db.Usuario
from Relaciones in db.Relaciones
where Relaciones.Cursos.idCurso == id
select distinct Usuario;
but the distinct in select usuario shoots me an error

To emulate the distinct sql clause using linq you need to use the distinct method which returns distinct elements from a sequence by using the default equality comparer to compare values.
var query = (from Usuario in db.Usuario
join Relaciones in db.Relaciones on Usuario.idUsuario = Relaciones.idUsuario
join Cursos in db.Cursos on Relaciones.idCurso = Cursos.idCurso
where Cursos.idCurso == id
select Usuario).Distinct();

Related

translate postgres sql to linq. Is it possible?

I need translate next sql to linq is it possible? That will have approximately the same speed
SELECT Count(tblcollectionimage.lngimageid),
tblcollectiontree.lngcollectionid,
tblcollection.txtname
FROM (tblcollectiontree
LEFT JOIN tblcollectionimage
ON blcollectiontree.lngcollectionid =
tblcollectionimage.lngcollectionid)
JOIN tblcollection
ON tblcollectiontree.lngcollectionid = tblcollection.lngcollectionid
WHERE lngcollectionparentid = 0
GROUP BY tblcollectiontree.lngcollectionid,
tblcollection.txtname
I have currently such linq but it doesn't work.
var results =(from collection in dataBase.tblcollections
join collectionTree in dataBase.tblcollectiontrees on
collection.lngcollectionid equals collectionTree.lngcollectionid
into generalCollections
from generalCollection in generalCollections
join images in dataBase.tblcollectionimages on
collection.lngcollectionid equals images.lngcollectionid
into generalCollectionImages
from generalCollectionImage in
generalCollectionImages.DefaultIfEmpty()
group generalCollectionImage by
generalCollectionImage.lngcollectionid into hello
from hellos in hello.DefaultIfEmpty()
join collection in dataBase.tblcollections on
hello.Key equals collection.lngcollectionid
select new
{
id = hello.Key,
name = hello.Count()
}).ToList();

Linq to SQL Query with fk

I try to realize this query from T-SQL in Linq to SQL:
Select * from RPG r
join RPGPlayer e on r.RPGID = e.RPGID
join [User] i on e.UserID = i.UserID
where i.Username like '%Dunkel%'
The result is correct for 2 Rows on SQL-Query itself.
I try this:
rpgList.Where(y => y.RPGPlayers == y.RPGPlayers.Where(e => e.User.Username.Contains(player))).ToList();
(rpgList is a list of the complete table loaded before)
Not entirely sure regarding the question, but the following is my attempt to represent the SQL join statement in LINQ …
from r in RPG
join e in RPGPlayer on r.RPGID equals e.RPGID
join i in User on e.UserID equals i.UserID
where i.Username.Contains("Dunkel")

Inner join using LINQ on DataTables

I have these 2 DataTables, customerTableDT and customerAliasesTableDT. They are both populated from a database like this:
customerTableDT = UtilityDataAndFunctions.PerformDBReadTransactionDataTableFormat(String.Format("SELECT * FROM {0}", TableNames.customers));
customerAliasesTableDT = UtilityDataAndFunctions.PerformDBReadTransactionDataTableFormat(String.Format("SELECT * FROM {0}", TableNames.customerAliases));
Now I'm trying to do an inner join on the two datatables like this:
var customerNames = from customers in customerTableDT.AsEnumerable()
join aliases in customerAliasesTableDT.AsEnumerable on customers.Field<int>("CustomerID") equals aliases.Field<int>("CustomerID")
where aliases.Field<string>("Alias").Contains(iString) select customers.Field<string>("Name")
But it gives me this error:
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.
If I had to write in SQL about what I'm trying to do, its very simple:
SELECT * FROM CUSTOMERS C
INNER JOIN CustomerAliases ALIASES ON ALIASES.CustomerID = C.CustomerID
WHERE CA.Alias LIKE %STRING_HERE%
Any help ?
You missed brackets after AsEnumerable, so it's treated as Method Group, not IEnumerable<DataRow>:
var customerNames = from customers in customerTableDT.AsEnumerable()
join aliases in customerAliasesTableDT.AsEnumerable() on customers.Field<int>("CustomerID") equals aliases.Field<int>("CustomerID")
where aliases.Field<string>("Alias").Contains(iString) select customers.Field<string>("Name")

Can't convert T-SQL INNER JOIN to LINQ-Entities query

T-SQL:
declare #postlocations table (locationid int)
insert into #postlocations
select locationid
from dbo.PostLocations
where PostId = 162172
select t.*
from dbo.Themes t
inner join dbo.ThemeLocations tl on t.ThemeId = tl.ThemeId
inner join #postlocations pl on tl.LocationId = pl.locationid
LINQ-Entities i have so far:
var postLocations = e.SomePost.Locations; // pre-fetched, e.g materialized ICollection<Post>
var themes = (from t in db.Themes
join q in postLocations on t.Locations.Select(l => l.LocationId) equals q.LocationId
select t).ToList();
But the compiler is complaining on the join keyword about not being able to infer the type arguments.
Any ideas?
I don't think you can join a SQL table with an in-memory list of objects, even if those objects are originally from the database.
Convert the in-memory list of objects to a list of id's (integer), and use that in the join or in a Contains/sub-select. EF can translate the list of id's to parameters when generating the SQL.
The problem with your join is that you're implying a collection of LocationId (t.Locations.Select(l => l.LocationId) can equal a single LocationId. You're trying to join a Theme which has a collection of Locations onto a single Location.
You should be able to fix this by using Contains
var themes = (from t in db.Themes
join q in postLocations
on t.Locations.Select(l => l.LocationId).Contains(q.LocationId)
select t).ToList();
or if EF complains about passing a postLocations as a parameter, you can try
// I'd materialize this but you may not have to
var postLocationIds = postLocations.Select(p => p.LocationId).ToList();
var themes = db.Themes.Where(t => t.Locations.Any(l =>
postLocationIds.Contains(l.LocationId))).ToList();
Edit
how about this
///your sql query
select t.* from dbo.Themes t
inner join dbo.ThemeLocations tl on t.ThemeId = tl.ThemeId
inner join #postlocations pl on tl.LocationId = pl.locationid
//linq query for that
from t in teams
join from tl in teamlocation on t.themid = tl.ThemeID
join from pl in postlocation on tl.temeid = pl.temeid
select t;
Org
Not sure but you can try out by using let keyword
var themes = (from t in db.Themes
let location = t.Locations
join q in postLocations on location.LocationId equals q.LocationId
select t).ToList();

Linq to SQL Joining to the Same Table Twice for Two Different Tables

How do I write this SQL in Linq to SQL using C#. I cannot get the join to the status table to both ConsumerApplications and RepairOrderEstimates to work properly. Thanks.
select ca.ConsumerAppID,
ca.LastName,
statConsumerApp.StatusName,
statRepairOrderEstimates.StatusName
from ConsumerApplications ca
join RepairOrderEstimates
on ca.RepairOrderEstimateID = RepairOrderEstimates.RepairOrderEstimateID
join Statuses statConsumerApp
on ca.StatusID = statConsumerApp.StatusID
join Statuses statRepairOrderEstimates
on RepairOrderEstimates.StatusID = statRepairOrderEstimates.StatusID
I think you can do this with something like
from ca in ConsumerApplications
join est in RepairOrderEstimates on ca.RepairOrderEstimateID == est.RepairOrderEstimateID
join statConsumerApp in Statuses on ca.StatusID == statConsumerApp.StatusID
join statEstimate in Statuses on est.StatusID == statEstimate.StatusID
select new {
ConsumerAppID = ca.ConsumerAppID,
LastName = ca.LastName,
AppStatus = statConsumerApp.StatusName,
EstimateStatus = statEstimate.StatusName,
}

Categories

Resources