[英]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.