[英]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. 我正在以代码为中心,从以SQL为中心的世界(我相当熟练)到EF dDbContect,而我一直在挣扎。 The following is a simplified example;
以下是一个简化的示例; I want to write the following simple SQL query (which took 60 seconds to write):
我想编写以下简单的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'
as an EF style query. 作为EF样式查询。 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.
我看不到该怎么做,也不想每次都看不到该做些什么时就退回到SQL。
Can anyone help: 谁能帮忙:
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()
). 当然,必须通过遍历结果(或使用
.ToList()
/ .ToArray()
)来实现此查询。
To define the entities and context properly, refer to this excellent tutorial on MSDN: http://msdn.microsoft.com/en-us/data/jj193542 . 要正确定义实体和上下文,请参考MSDN上的出色教程: http : //msdn.microsoft.com/zh-cn/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. 首先尝试一些Linq。 You can write it as below.
您可以如下编写。 The query might have some mistake, it will be corrected by Intellisense.
该查询可能有一些错误,它将被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 为了获得一些示例的好地方,我建议使用101个linq样本
It has everything from using a WHERE to GROUP BY statements. 它具有从使用WHERE到GROUP BY语句的所有功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.