简体   繁体   中英

Moving from SQL to Entity Framework Code First

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:

  • On how to frame the above query in EF dbContent
  • On a general source of help with

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 .

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);

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM