Entity Framework 6 Recipes 2nd Edition(11-11)译 -> 在LINQ中调用数据库函数

11-11. 在LINQ中调用数据库函数

问题

相要在一个LINQ 查询中调用数据库函数.

解决方案

假设有一个任命(Appointment )实体模型,如Figure 11-11.所示, 我们想要查询某周给定的一天里的所有appointment.

 

Figure 11-11. An Appointment entity with the start and end times for appointments

如果我们想要找出所有周四的appointment, 我们不能在where子句里,使用运行时枚举DayOfWeek.Thursday与StartsAt属性比较,因为这样是不能翻译成数据库语句.

我们需要像下列的Listing 11-18这样操作:

Listing 11-18. Using a Database Function in a LINQ Query

class Program

{

static void Main(string[] args)

{

RunExample();

}

static void RunExample()

{

using (var context = new EFRecipesEntities())

{

var app1 = new Appointment

{

StartsAt = DateTime.Parse("7/23/2013 14:00"),

GoesTo = DateTime.Parse("7/23/2013 15:00")

};

var app2 = new Appointment

{

StartsAt = DateTime.Parse("7/24/2013 9:00"),

GoesTo = DateTime.Parse("7/24/2013 11:00")

};

var app3 = new Appointment

{

StartsAt = DateTime.Parse("7/24/2013 13:00"),

GoesTo = DateTime.Parse("7/23/2013 15:00")

};

context.Appointments.Add(app1);

context.Appointments.Add(app2);

context.Appointments.Add(app3);

context.SaveChanges();

}

using (var context = new EFRecipesEntities())

{

var apps = from a in context.Appointments

where SqlFunctions.DatePart("WEEKDAY", a.StartsAt) == 4

select a;

Console.WriteLine("Appointments for Thursday");

Console.WriteLine("=========================");

foreach (var appointment in apps)

{

Console.WriteLine("Appointment from {0} to {1}",

appointment.StartsAt.ToShortTimeString(),

appointment.GoesTo.ToShortTimeString());

}

}

}

}

上述Listing 11-18代码输出结果如下:

Appointments for Thursday

=========================

Appointment from 9:00 AM to 11:00 AM

Appointment from 1:00 PM to 3:00 PM

它是如何工作的?

数据库函数可用于eSQL 和LINQ 查询中. 这些函数通过

SqlFunctions 类里的方法发布出来.由于这些函数运行在数据库端, 所以它的表现方式可能与你在.net端想的表现方式会有所不同,例如周四,在.NET里 DayOfWeek.Thursday 的值是4.而在数据库, 它是第5天,所以它的值是5.

与数据库函数在eSQL中使用一样,不是所有的数据库函数都被LINQ查询支持,可以从微软的文档中查看所有支持的函数列表.

 

附:创建示例用到的数据库的脚本文件

 

posted @ 2016-01-25 23:40  kid1412  阅读(497)  评论(0编辑  收藏  举报