【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.DateTime>' to 'System.DateTime'无法将类型“System.Collections.Generic.IEnumerable<System.DateTime>”隐式转换为“System.DateTime”
【发布时间】:2019-05-24 09:06:40
【问题描述】:

我想从数据库中选择一个日期时间格式的数据。

我有 3 个模型。

School

        public int Id { get; set; }

        public ICollection<SchoolStore> SchoolStores { get; set; }
SchoolStores

        public int SchoolId { get; set; }

        public School School { get; set; }

        public ICollection<Event> Events { get; set; }
Events

        public DateTime Date { get; set; }

        public EventStatus Status { get; set; }

方法看起来像


 public IQueryable<SchoolProjectionModel> GetAllForList()
        {
            return dataContext.Schools.AsNoTracking().IgnoreQueryFilters()
                .Select(s => new SchoolListProjectionModel()
                {                 
                  publishedEventDate = s.SchoolStores.Select(ss => ss.Events
                                                      .Where(ee => ee.Status == EventStatus.Published && ee.SchoolId == s.Id)
                                                       .Select(ed => ed.Date)
                                                        .Where(ses => ses.Date >= DateTime.Today))

                });
        }

但我收到这样的错误

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.DateTime>' 
to 'System.DateTime'

我希望从数据库中接收日期时间格式的数据。

SchoolListProjectionModel

using System.Collections.Generic;
using System;
    public class SchoolListProjectionModel
    {

        public DateTime publishedEventDate { get; set; }

    }

【问题讨论】:

  • 请告诉我们SchoolListProjectionModel
  • 用模型更新了我的问题
  • 在最后一个.where 之后添加.First().FirstOrDefault()
  • 只需将 .Where(condition) 替换为 .FirstOrDefault(condition) 即可获得单个日期而不是日期列表
  • 我尝试添加和替换,但没有任何改变

标签: asp.net entity-framework linq asp.net-core


【解决方案1】:

答案是

                publishedEventDate = s.SchoolStores.SelectMany(ss => ss.Events
                                                        .Where(e => e.Status == EventStatus.Published && e.SchoolId == s.Id)
                                                                .Select(ed => ed.Date)
                                                                        .Where(eed => eed.Date >= DateTime.Today && eed.Date != null)).FirstOrDefault()

【讨论】:

    【解决方案2】:
                  publishedEventDate = s.SchoolStores.Select(ss => ss.Events
                                                      .Where(ee => ee.Status == EventStatus.Published && ee.SchoolId == s.Id && ee.Date >= DateTime.Today).Select(p=>p.Date)).FirstOrDefault()
    

    【讨论】:

    • @zeng tian 你也应该添加一些解释。
    猜你喜欢
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 2023-01-18
    • 2011-05-28
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多