Reputation: 5550
I am making the journey from an SQL centric world (where I am reasonably fluent) to EF dDbContect with code first and I am struggling. The following is a simplified example; I want to write the following simple SQL query (which took 60 seconds to write):
SELECT
HP.HospitalID
FROM
Hospitals AS HP
JOIN NHSTrusts AS NT
ON NT.NHSTrustID = HP.NHSTrust_NHSTrustID
WHERE
HP.HospitalName + ', ' + NT.NHSTrustName = 'My hospital name including trust'
as an EF style query. I cannot see how to do this and I don't want to drop back into SQL everytime I cannot see how to do something.
Can anyone help:
Upvotes: 2
Views: 127
Reputation: 37760
Assuming these entity types:
public class Trust
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Hospital> Hospitals { get; set; }
}
public class Hospital
{
public int Id { get; set; }
public string Name { get; set; }
public int TrustId { get; set; }
public Trust Trust { get; set; }
}
you'll have this query:
dbContext
.Hospitals
.Where(h => h.Name + h.Trust.Name == "My hospital name including trust")
.Select(h => h.Id);
Upvotes: 2
Reputation: 40506
Assuming your entities and DB Context are properly set, here's how your query may look like:
var hospitalIds =
from hp in dbContext.Hospitals
where
hp.HospitalName == "..." &&
hp.Trust.NHSTrustName == "..."
select hp.HospitalId;
Of course, this query will have to be materialized by iterating through the results (or by using .ToList()
/.ToArray()
).
To define the entities and context properly, refer to this excellent tutorial on MSDN: http://msdn.microsoft.com/en-us/data/jj193542.
Upvotes: 3
Reputation: 3315
For a good place to get some examples i would recommend 101 linq samples
It has everything from using a WHERE to GROUP BY statements.
Upvotes: 0
Reputation:
First try some Linq. You can write it as below. The query might have some mistake, it will be corrected by Intellisense.
var s = (from c in Context.Hospitals
from h in Context.NHSTrusts
where c.NHSTrust_NHSTrustID==h.NHSTrustID
&& string.Format("{0},{1}",c.HospitalName,h.NHSTrustName).Equals("My hospital name including trust")
select c.HospitalId).FirstOrDefault();
Upvotes: 1