【问题标题】:Argument 2: cannot convert from 'bool' to 'System.DateTime?'参数 2:不能从 'bool' 转换为 'System.DateTime?'
【发布时间】:2020-03-26 14:48:12
【问题描述】:

我尝试在两个日期之间创建一个数据范围:开始和结束。

为此,我有以下查询:

public DateTime CreatedAt { get; set; }

private IQueryable<Alert> GetAlerts(int organisationId, DateTime? beginDate = null, DateTime? endDate = null,  bool includeDone = false)
{
    var query = 
        _patientDbContext.Alerts
            .Where(i => i.OrganisationId == organisationId && i.CreatedAt = endDate.ToString() <= beginDate.ToString());

    if (!includeDone)
    {
       query = query.Where(i => !i.IsDone);
    }

    query = query.OrderBy(i => i.Deadline);

    return query;
}

但我收到此错误:

参数 2:无法从 'bool' 转换为 'System.DateTime?'

我做错了什么?

【问题讨论】:

  • i.CreatedAt = endDate.ToString() 是一个assignemtn,没有比较。这是故意的还是错字?我认为这是有意为之,这会使您的 Where 产生非常烦人的副作用。
  • 这在很多层面上都是错误的i.CreatedAt = endDate.ToString() &lt;= beginDate.ToString() 1.CreatedAt 是 prooblay 布尔值,endDate.ToString() 是字符串 2.. 我认为你的意思是 == 而不是 =

标签: c# linq type-conversion


【解决方案1】:

您在 CreatedAt 上执行的操作是错误的。如下更改。

var query = _patientDbContext.Alerts
            .Where(i => i.OrganisationId == organisationId && (i.CreatedAt < endDate &&  i.CreatedAt > beginDate));

【讨论】:

    【解决方案2】:

    这是因为您的 Where 子句中有一个赋值(= 符号)

    i.CreatedAt = endDate.ToString() <= beginDate.ToString()
    

    你想做的是这个,假设CreatedAtDateTime

    var query = _patientDbContext.Alerts.Where(i =>
        i.OrganisationId == organisationId &&
        (beginDate == null || i.CreatedAt => beginDate.Value) &&
        (endDate == null || i.CreatedAt <= endDate.Value)
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-13
      • 2017-11-12
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 2015-04-25
      • 2021-01-02
      相关资源
      最近更新 更多