使用LINQ to Entities来写查询语句
Entity Framework查询是使用的.NET Framework功能Language Integrated Query,AKA LINQ。LINQ与.NET的编程体验是紧密集成在一起的,它提供了强类型的查询,何谓强类型,各位自行补脑。与弱类型的查询相比,它提供了编译时检查来保证你的查询通过验证以及IntelliSense。
LINQ是一个通用的查询框架,并不仅仅是针对Entity Framework或者数据库的,LINQ提供程序负责把LINQ查询转换成对数据的查询并返回结果,对Entity Framework来说这个提供程序就是LINQ to Entities,它负责把LINQ查询转换成对数据库的SQL查询,你提供给EF关于你的模型的信息以及模型如何映射到数据的的信息都会用来执行这个转换,一旦查询返回,EF就负责把结果数据返回给你的模型(拷贝数据给你的模型实例)。
注意除了LINQ,EF也支持基于文本的查询,这就是Entity SQL或者叫ESQL。ESQL通常使用在更高级的场景中:需要在运行时动态构造查询。当然有同学也会提到表达式树,是的。因为ESQL是基于文本的,所以当应用程序需要创建对在运行时尚未知道的模型的查询语句时也是有用的。鉴于ESQL不太常用,它不是直接由DbContext API提供的,如果你的应用程序需要使用ESQL,你需要通过ObjectContext API使用IObjectContextAdapter接口。
下面为了演示DbContext查询方面的功能我们建立下面几个Model以及Context
publicclass Destination
2 {
3 public Destination()
4 {
5 this.Lodgings = new List<Lodging>();
6 }
7
8 [Column("LocationID")]
9 public int DestinationId { get; set; }
10 [Required, Column("LocationName")]
11 [MaxLength(200)]
12 public string Name { get; set; }
13 public string Country { get; set; }
14 [MaxLength(500)]
15 public string Description { get; set; }
16 [Column(TypeName = "image")]
17 public byte[] Photo { get; set; }
18 public string TravelWarnings { get; set; }
19 public string ClimateInfo { get; set; }
20
21 public virtual List<Lodging> Lodgings { get; set; }
22 }
2 {
3 public int LodgingId { get; set; }
4 [Required]
5 [MaxLength( 200)]
6 [MinLength( 10)]
7 public string Name { get; set; }
8 public string Own