首页 > 数据库技术 > 详细

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

时间:2016-01-26 00:20:06      阅读:285      评论:0      收藏:0      [点我收藏+]

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查询支持,可以从微软的文档中查看所有支持的函数列表.

 

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

 

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

原文:http://www.cnblogs.com/kid1412/p/5159065.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!