【问题标题】:Retrieve the last 5 years data using Entity Framework Linq使用 Entity Framework Linq 检索过去 5 年的数据
【发布时间】:2016-06-28 03:27:54
【问题描述】:

我需要在以下查询中检索过去 5 年的数据。你能告诉我该怎么做吗?

 var propertyIdList = (from property in _context.Properties
                       .Where(p => p.CreationTime >= condition for 5 years data restriction)
                        select new PropertyIdListDto
                                    {
                                        Id = property.Id,
                                    }).OrderBy(p => p.Id).AsNoTracking().ToList();

我知道如何用 TSQL 做到这一点。但我需要用 Linq 做到这一点。

TSQL(示例):

SELECT *
  FROM products
 WHERE date_column >= add_months( sysdate, -12*5 )

【问题讨论】:

  • p.CreationTime >= DateTime.Now.AddYears(-5)
  • 使用 EntityFuctions.AddYears 或 DbFunctions

标签: sql-server entity-framework linq entity-framework-6


【解决方案1】:

试试这样的,

var fiveYearsBackDate = DateTime.Now.AddYears(-5);
var propertyIdList = (from property in _context.Properties
                       .Where(p => p.CreationTime >= fiveYearsBackDate)
                        select new PropertyIdListDto
                                    {
                                        Id = property.Id,
                                    }).OrderBy(p => p.Id).AsNoTracking().ToList();

【讨论】:

  • 它给出了这个运行时异常:你能告诉我为什么吗? System.NotSupportedException: LINQ to Entities does not recognize the method 'System.DateTime AddYears(Int32)' method, and this method cannot be translated into a store expression.
  • 不要像我在示例中所做的那样将其添加到单独计算日期。
  • 哦..知道了。非常感谢:)
  • 很高兴为您提供帮助,如果您对它感到满意,请接受答案。
猜你喜欢
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多