EF中关于日期字值的处理

一、SQL语句方式

   var datefrom = DateTime.Parse(fromdate);
   var dateto = DateTime.Parse(todate);

  var sql = string.Format("insert into {0}(id,regionid,fromdate,todate,createdate) values('{1}','{2}',{3},{4},{5})", typeof(DownloadHistory).Name, taskid, region.ID,datefrom,dateto,DateTime.Now);
  int i = dbContext.Database.ExecuteSqlCommand(sql);

 

   执行时,报错:System.Data.SqlClient.SqlException:“Incorrect syntax near '0'.”

  需改成以下方式来执行:

object objFrom = datefrom;
object objTo = dateto;
object objNow = DateTime.Now;
var sql = string.Format("insert into {0}(id,regionid,fromdate,todate,createdate) values('{1}','{2}',@fromdate,@todate,@createdate)", typeof(DownloadHistory).Name, taskid, region.ID);
var parameters = new SqlParameter[]
{
new SqlParameter("@fromdate",objFrom),
new SqlParameter("@todate",objTo),
new SqlParameter("@createdate",objNow)
};
int i = dbContext.Database.ExecuteSqlCommand(sql, parameters);

 

二、DateTime?类型字段的处理(日期为空)

  (1) 如果使用EF语句来执行,必须使用以下语法:

   DateTime? ohzrq = null;  //ef用法

  (2)如果是SQL语句来执行,必须使用以下语法:

   object ohzrq = DBNull.Value;

 

posted @ 2018-11-10 02:17  SimpleGIS  阅读(938)  评论(0编辑  收藏  举报