zoukankan      html  css  js  c++  java
  • 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查询支持,可以从微软的文档中查看所有支持的函数列表.

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

  • 相关阅读:
    剑指Offer——矩形覆盖
    剑指Offer——变态跳台阶
    ASCII table and description .
    字符编解码的故事(ASCII,ANSI,Unicode,Utf-8区别) .
    tchar 输入输出类 和 string 类 函数简单说明 总结各种前缀后缀
    各种 C++编译器的性能对比
    怎样写参数个数可变的宏 Debug宏 Log宏等
    C语言中的可变参数函数 三个点“…”printf( const char* format, ...)
    常用C语言字符串操作函数
    Multi-Byte Character Set & Use Unicode Character Set .
  • 原文地址:https://www.cnblogs.com/kid1412/p/5159065.html
Copyright © 2011-2022 走看看