Entity Framework 支持三种类型的数据库查询。
- LINQ to Entities
- Entity SQL
- Native SQL
其中,LINQ(音:link)是较为推荐的方式。它又分为 LINQ Method syntax 与 LINQ Query syntax,如下所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// LINQ Method syntax using (var context = new CompanyDBEntities()) { var L2EQuery = context.Employees.where(e => e.EmployeeName== "Ben"); var employee= L2EQuery.FirstOrDefault(); } // LINQ Query syntax using (var context = new CompanyDBEntities()) { var L2EQuery = from ep in context.Employees where ep.EmployeeName == "Bill" select ep; var employee = L2EQuery.FirstOrDefault(); } |
Entity SQL 与 Native SQL 都是基于拼接 SQL 语句的方式,如下所示。
1 2 3 4 5 6 7 8 9 10 11 |
// Entity SQL string sqlString = "SELECT VALUE ep FROM CompanyDBEntities.Employees " + "AS ep WHERE ep.EmployeeName == 'Ben'"; var objctx = (ctx as IObjectContextAdapter).ObjectContext; ObjectQuery employee = objctx.CreateQuery(sqlString); Employee newEmployee = employee.First(); // Native SQL using (var ctx = new CompanyDBEntities()) { var employeeName = ctx.Employees.SqlQuery("Select EmployeeId, EmployeeName from Employee where EmployeeName='Ben'").FirstOrDefault(); } |
此外,Entity Framework 提供了丰富的函数,应了解并掌握用法。以下列举一些。
- Aggregate*
- Average
- All
- Any
- ElementAt/ElementAtOrDefault*
- Single/SingleOrDefault*
- Contains
- First/FirstOrDefault/Last/LastOrDefault*
- Count
- Max/Min*
- OrderBy/OrderByDescending
- Reverse
- SelectMany
- SequenceEqual
- Skip/SkipWhile
- Take/TakeWhile
其中以星号标记的将返回 Entity 实体。