LINQ从DateTime列中选择MonthId和MonthName

LINQ select MonthId and MonthName from DateTime column
2021-06-10
  •  译文(汉语)
  •  原文(英语)

我在从db的DateTime列中选择MonthId和MonthName时遇到问题.我已经试过了 它会编译,但是运行时错误"对实体的linq无法识别方法'System.String.ToString()'"

var months = bookings.Select(c => new { 

                MonthId = c.ActualEta.Value.Month,
                MonthName = c.ActualEta.Value.Month.ToString("MMMM")
        }).ToList();

任何人?在这里,ActualEta是可为空的日期时间.

解决过程1
var months = bookings
    .AsEnumerable()
    .Select(c => new { 
        MonthId = c.ActualEta.Value.Month,
        MonthName = c.ActualEta.Value.Month.ToString("MMMM")
    }).ToList();

请注意AsEnumerable(),这实际上将查询从LinqToEntities转换为LinqToObjects,从而使您可以使用诸如的非SQL方法ToString().

速聊1:
示例:"c.ActualEta.Value.ToString("MMMM")",不具有"月"属性.谢谢.
解决过程2
var months = bookings.Select(c => new { 
     MonthId = ((DateTime)c.ActualEta.Value).Month,
     MonthName = ((DateTime)c.ActualEta.Value).ToString("MMMM")
}).ToList();

I'm having trouble selecting MonthId and MonthName from a DateTime column in db. I've tried this. It compiles but runtime error "linq to entities does not recognize the method 'System.String.ToString()'"

var months = bookings.Select(c => new { 

                MonthId = c.ActualEta.Value.Month,
                MonthName = c.ActualEta.Value.Month.ToString("MMMM")
        }).ToList();

Anyone? ActualEta is an nullable datetime here.

Solutions1
var months = bookings
    .AsEnumerable()
    .Select(c => new { 
        MonthId = c.ActualEta.Value.Month,
        MonthName = c.ActualEta.Value.Month.ToString("MMMM")
    }).ToList();

Note the AsEnumerable(), this essentially converts the query from LinqToEntities to LinqToObjects, allowing you to use non-SQL methods like ToString().

Talk1:
Example: "c.ActualEta.Value.ToString("MMMM")", without "Month" property. Thanks.
Solutions2
var months = bookings.Select(c => new { 
     MonthId = ((DateTime)c.ActualEta.Value).Month,
     MonthName = ((DateTime)c.ActualEta.Value).ToString("MMMM")
}).ToList();
转载于:https://stackoverflow.com/questions/19081409/linq-select-monthid-and-monthname-from-datetime-column

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入