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;

上一篇:windform 重绘Treeview "+-"号图标


下一篇:Android Dex文件格式(一)