[英]Moving from SQL to Entity Framework Code First
我正在以代碼為中心,從以SQL為中心的世界(我相當熟練)到EF dDbContect,而我一直在掙扎。 以下是一個簡化的示例; 我想編寫以下簡單的SQL查詢(編寫花費了60秒):
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'
作為EF樣式查詢。 我看不到該怎么做,也不想每次都看不到該做些什么時就退回到SQL。
誰能幫忙:
假設您的實體和數據庫上下文已正確設置,則查詢如下所示:
var hospitalIds =
from hp in dbContext.Hospitals
where
hp.HospitalName == "..." &&
hp.Trust.NHSTrustName == "..."
select hp.HospitalId;
當然,必須通過遍歷結果(或使用.ToList()
/ .ToArray()
)來實現此查詢。
要正確定義實體和上下文,請參考MSDN上的出色教程: http : //msdn.microsoft.com/zh-cn/data/jj193542 。
假設這些實體類型:
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; }
}
您將得到以下查詢:
dbContext
.Hospitals
.Where(h => h.Name + h.Trust.Name == "My hospital name including trust")
.Select(h => h.Id);
首先嘗試一些Linq。 您可以如下編寫。 該查詢可能有一些錯誤,它將被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();
為了獲得一些示例的好地方,我建議使用101個linq樣本
它具有從使用WHERE到GROUP BY語句的所有功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.