Linq To Sql - Get week day name from date

孤人 提交于 2021-01-27 18:43:40

问题


Is it possible to construct a query in which I can retrieve week day name from a date into a separate column or variable?

I know I can very easily do this on .NET side but would like it to be in the query.


回答1:


You can also use SqlFunctions...

var results=context.Listings
  .Select(l=>System.Data.Entity.SqlServer.SqlFunctions.DateName("dw",l.modify_date));

Of course, this only works when using a SQL Server. Methods that are cross-database, would be to use EntityFunctions.DateDiff with a known date to get the number of days between whatever and a known prior sunday, then modulus 7, then convert to a string.




回答2:


It is possible you will need to build your query which returns day names and then join to your result on day number

int[] dayNum={1,2,3,4,5,6,7};

var result = from d in dayNum
    let dayOfWeek= (d == 1 ? "Monday" :
            d==2 ? "Tuesday" :
            d==3 ? "Wednesday" :
            d==4 ? "Thursday" :
            d==5 ? "Friday" :
            d==6 ? "Saturday" :
            d==7 ? "Sunday":"")
   let dn = d
 group d by new {dayOfWeek, dn} into dw
 select new { dw.Key.dayOfWeek, dw.Key.dn};

The result of this will be

enter image description here



来源:https://stackoverflow.com/questions/30729913/linq-to-sql-get-week-day-name-from-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!