无法将类型'System.Collections.Generic.IEnumerable <system.datetime>'隐式转换为'System.DateTime'

时间:2019-05-24 09:06:40

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

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

我有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; }

    }

2 个答案:

答案 0 :(得分:0)

答案是

                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()

答案 1 :(得分:-1)

              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()