get date part only from datetime value using entit

2019-02-17 04:39发布

I want to get date part only from database 'date time' value I m using the below code..but it is getting date and time part.

using (FEntities context = new FEntities())
{
    DateTime date = DateTime.Now;
    if (context.tblvalue.Any(x => x.date == date))
    {    
    }
}

3条回答
【Aperson】
2楼-- · 2019-02-17 04:59
context.Database.SqlQuery<T>(sql, sql_parameters)

accepts pure SQL in the first parameter. Use MS SQL server's function CONVERT(VARCHAR(6), date_value, 112) AS MonthYYYYmm for retrieving year with month.

查看更多
走好不送
3楼-- · 2019-02-17 05:06

With entity framework 6 and update use

context.tblvalue.Any(x => DbFunctions.TruncateTime(x.date) == data.Date);
查看更多
SAY GOODBYE
4楼-- · 2019-02-17 05:17

You can compare just specified parts:

context.tblvalue.Any(x => x.date.Year == data.Year 
                        && x.date.Month == data.Month 
                        && x.date.Day == data.Day);

EDIT: You can also try the following:

context.tblvalue.Any(x => EntityFunctions.TruncateTime(x.date) == data.Date);

Another approach:

context.tblvalue.Any(x =>  SqlFunctions.DatePart("year", x.date)  == data.Year 
                        && SqlFunctions.DatePart("month", x.date) == data.Month 
                        && SqlFunctions.DatePart("day", x.date)   == data.Day);
查看更多
登录 后发表回答