【问题标题】:Call a Linq to SQL user defined function multiple times in one trip to the DB在一次访问数据库中多次调用 Linq to SQL 用户定义函数
【发布时间】:2013-09-20 18:22:29
【问题描述】:

我有一个用户定义的函数,它接受 2 个日期时间参数并返回一个短值。

我已将它添加到我的 Linq to Sql 模型中,这意味着我有如下函数:

private short? Aqua_NumShopDays(System.Nullable<System.DateTime> start,
                                System.Nullable<System.DateTime> end)

所以,我的问题是,我怎样才能轻松地(以 LINQy 类型的方式)为多个日期对调用它,这只会导致一次数据库访问?

如果需要而不是日期列表,如果第一个参数是固定的,第二个参数是给定范围内的每个值,它仍然很有用。

【问题讨论】:

    标签: c# sql-server linq linq-to-sql


    【解决方案1】:

    到目前为止我发现的最好的方法是创建一个具有一系列数字的表(或创建一个的用户函数),然后在 Linq-To-SQL 中使用它,如下所示:

    // NumberRange is my user defined function, that returns a table with all a row per number
    // Here I take that number and calculate the date based on an offset from today
    var test = from dayOffset in ARDC.NumberRange(1, 10)
               select DateTime.Today.AddDays(dayOffset.Counter.Value); // Counter is the column name of the table returned
    
    // Using the dates, that are calculated on the server, I select a call to the SQL function
    var testResults = from toDate in test
                      select ARDC.Aqua_NumShipDays(DateTime.Today, toDate).Value;
    
    var t = testResults.ToList(); // This results in ONE trip to the database! (yay!)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      相关资源
      最近更新 更多