Using LINQ to SQl to achieve column Query - sql

Can the below query be achieved with LINQ to SQL?
select id,
(select StateName from b_mstates where id=StateIdFk) as [State Name],
CityName
from b_mcities

var result = b_mcities.where(x => b_mstates.where(y => y.id == StateIdFK)
.contains(x.statename)).ToList();
Your question is pretty tough, because your sql wont run(it is malformed and missing logic). this is the jist of what you will need to do.

Assuming you have your associations set up correctly, it should be as simple as
var result = from city in m_bcities
select new {city.id, city.State.StateName, city.CityName}

Related

How to change the following SQL query to a Linq query

How to change the following SQL query to Linq query and how to convert results to a list of strings?
select Name
from Categories
where ID in (select CID from CategoryLink where VID = 57)
Please, provide some extra context. From the fist sight the code should be something like this:
List<string> names = db.Categories
.Where(c => db.CategoryLink.Any(cl=>cl.VID == 57 && CID == c.ID))
.ToList();

How to get the latest/last record with a group by clause with NHibernate Linq provider

I have used too much time (days) on this and I really hope someone can help me out.
I found a good article on describing my problem in a generic way so let's stick to it.
I am trying to build this query but NHibernate fails to build the correct sql and returns a sql query exception.
Column vSagsAendring.Id is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. It could not execute the following query:
select
viewsagsae0_.Id as Id155_,
viewsagsae0_.SagId as SagId155_,
viewsagsae0_.JournalNr as JournalNr155_,
viewsagsae0_.LbfNr as LbfNr155_,
viewsagsae0_.OrgNr as OrgNr155_,
viewsagsae0_.OrgNavn as OrgNavn155_,
viewsagsae0_.AfdNavn as AfdNavn155_,
viewsagsae0_.SagsType as SagsType155_,
viewsagsae0_.Status as Status155_,
viewsagsae0_.SagsbehandlerInit as Sagsbeh10_155_,
viewsagsae0_.Dato as Dato155_,
viewsagsae0_.JournalAktionType as Journal12_155_,
viewsagsae0_.Beskrivelse as Beskriv13_155_,
viewsagsae0_.Ekstern as Ekstern155_
from vSagsAendring viewsagsae0_
group by viewsagsae0_.SagId
var query = from p in _session.Query<ViewSagsAendring>()
group p by p.SagId
into grp
select grp.OrderByDescending(g => g.Dato).First();
This is another version also took from the article:
var query = from p in _session.Query<ViewSagsAendring>()
group p by p.SagId
into grp
let maxDato = grp.Max(g => g.Dato)
from p in grp
where p.Dato == maxDato
select p;
It's have been a long journey, but now it's over. I hope that I can help someone else in the same situation by answering my own question.
var aendring = from sagsAendring in _session.Query<ViewSagsAendring>()
where sagsAendring.Dato ==
(
from innersagsAendring in _session.Query<ViewSagsAendring>()
where innersagsAendring.SagId == sagsAendring.SagId
select innersagsAendring.Dato
).Max()
select sagsAendring;
var result = aendring.ToList();
And because you can chain linq statements you can build a linq filter like this
if(Filters.VisInterneAendringer == false)
query = query.Where(x => x.Ekstern == true);
if (Filters.VisKunNyesteAendringer)
{
query = query.Where(sagsAendring => sagsAendring.Dato ==
(
from innerSagsAendring in Session.Query<ViewSagsAendring>() where innerSagsAendring.SagId == sagsAendring.SagId
select innerSagsAendring.Dato
).Max());
}
return query;
Your queries seem legit for LINQ in EntityFramework.
I'm not sure about hibernate, you might try to use QueryOver API instead of Query
http://nhibernate.info/blog/2009/12/17/queryover-in-nh-3-0.html

Convert Sql query with Group by and Having clause to Linq To Sql query in C#

I need help to convert following ql query to Linq to Sql query.
select Name, Address
from Entity
group by Name, Address
having count(distinct LinkedTo) = 1
Idea is to find all unique Name, Address pairs who only have 1 distinct LinkedTo value. Remember that there are other columns in the table as well.
I would try something like this:
Entity.GroupBy(e => new { e.Name, e.Address})
.Where(g => g.Select(e => e.LinkedTo).Distinct().Count() == 1)
.Select(g => g.Key);
You should put a breakpoint after that line and check the SQL that is generated to find what is really going to the database.
You could use:
from ent in Entities
group ent by new { ent.Name, ent.Address } into grouped
where grouped.Select(g => g.LinkedTo).Distinct().Count() == 1
select new { grouped.Key.Name, grouped.Key.Address }
The generated SQL does not use a having clause. I'm not sure LINQ can generate that.

How to put this Query into Linq (C#)?

I'm able to do:
var codeStation = from Code in ent.Role
where Code.Code.StartsWith("S_")
select Code;
(ent: being my Entity for my Database)
That gives me :
S_ANC
S_ATL
S_BNA
S_BOS
S_BRU
S_CLT
.....
S_YXE
S_YXY
S_YYC
S_YYG
S_YYT
S_YYZ
How can I accomplish the equivalent of the following SQL query?
SELECT Substring(Codes,3,6)
FROM Role
WHERE Codes LIKE 'S%'
Thanks!
var codeStation = from Code in ent.Role
where Code.Code.StartsWith("S_")
select RoleName.Substring(3,6);
Your LINQ query can select any legal C# expression you want, including method calls on the field names. So, you can do something like this:
var codeStation = from Code in ent.Role
where Code.Code.StartsWith("S_")
select Code.RoleName.SubString(3,6);

Converting SQL script to LINQ with IN clause

I am trying to work out how to covert the script below from SQL in to LINQ. Any help would be welcome.
SELECT *
FROM
[tableName]
WHERE
[MyDate] IN
(SELECT
MAX([MyDate])
FROM
[tableName]
GROUP BY
[MyID])
I can't find an equivalent for the "IN" clause section. There are existing questions on this forum but none that cover selecting a DateTime.
Thanks in advance.
You can use the ".Contains(..)" function:
e.g.
var itemQuery = from cartItems in db.SalesOrderDetails
where cartItems.SalesOrderID == 75144
select cartItems.ProductID;
var myProducts = from p in db.Products
where itemQuery.Contains(p.ProductID)
select p;
Although it looks like 2 round trips, as the LINQ only constructs the query when the IEnumerable is tripped, you should get reasonable performance.
I think Any() is what you are looking for:
var result = tableName.Where(x =>
(from t in tableName
group t by t.MyID into g
where g.Max(y => y.MyDate) == x.MyDate
select 1).Any())