简体   繁体   English

为什么我无法使用Entity Framework保存当前的DateTime.Now

[英]why i can't save the current DateTime.Now using Entity Framework

using (var transaction = new TransactionScope())
{
     using (var db = new MyEntities())
     {    
          var newGroup = new Groups
          {
              GroupDate = DateTime.Now,
              GroupName = "someName"
          };
          db.Groups.Add(newGroup);
          db.SaveChanges();
     }
     transaction.Complete();
 }

GroupId and GroupDate is PK, GroupId is Identity(step = 1) and GroupDate is not GroupId和GroupDate是PK,GroupId是Identity(步骤= 1)而GroupDate不是

can any one tell me why this exception happened when using a simple code like this and how to switch off the Optimistic Concurrency Updates if it's possible 任何人都可以告诉我为什么在使用像这样的简单代码时发生这种异常以及如果可能的话如何关闭乐观并发更新

Store update, insert, or delete statement affected an unexpected number of rows (0). 存储更新,插入或删除语句会影响意外的行数(0)。 Entities may have been modified or deleted since entities were loaded. 自实体加载后,实体可能已被修改或删除。 Refresh ObjectStateManager entries. 刷新ObjectStateManager条目。

It is most likely a problem of the different precisions of the .NET DateTime type and the column type you are using in SQL Server - probably datetime . 它很可能是.NET DateTime类型的不同精度和您在SQL Server中使用的列类型(可能是datetime

The INSERT statement that is sent to the database with SaveChanges looks like this: 使用SaveChanges发送到数据库的INSERT语句如下所示:

exec sp_executesql N'insert [dbo].[Groups]([GroupDate], [GroupName])
values (@0, @1)
select [GroupId]
from [dbo].[Groups]
where @@ROWCOUNT > 0 and [GroupId] = scope_identity() and [GroupDate] = @0',
N'@0 datetime2(7),@1 nvarchar(50)',
@0='2013-09-01 14:21:44.5156250',@1=N'someName'

The .NET DateTime stores 7 digits after the decimal point: .5156250 . .NET DateTime在小数点后存储7位数: .5156250 But the SQL datetime type cannot store this because it has less precision and some digits are cut off after storing the value. 但是SQL datetime类型不能存储它,因为它的精度较低,并且在存储值后会切断一些数字。 Hence, the comparison [GroupDate] = @0 in the where clause returns false and EF gets the info back that nothing has been stored (although the INSERT actually has been performed), cancels the transaction and throws the exception. 因此,比较[GroupDate] = @0where子句返回false和EF获取信息后面什么也没有存储(虽然实际上INSERT 执行),取消交易,并抛出异常。

As far as I can see you can solve this problem only by one of the following changes: 据我所知,您只能通过以下更改之一解决此问题:

  • Either remove GroupDate from the primary key, ie make it a non-key column 从主键中删除GroupDate非键列
  • Or change the type of the column in SQL Server to datetime2(7) which has the same precision as the .NET DateTime type 或者将SQL Server中的列类型更改为datetime2(7) ,其具有与.NET DateTime类型相同的精度
  • Or provide your GroupDate with less precision so that the value can be stored completely in a SQL datetime type without being cut off, for example only with seconds precision and the milliseconds being 0 : 或者为GroupDate提供较低的精度,以便可以将值完全存储在SQL datetime类型中而不会被截断,例如仅使用秒精度且毫秒为0

     var now = DateTime.Now; var date = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); var newGroup = new Groups { GroupDate = date, GroupName = "someName" }; 

    (There might be a smarter way to remove the milliseconds from a given DateTime value than the code above, but I couldn't find one right now.) (可能有一种更聪明的方法可以从给定的DateTime值中删除毫秒,而不是上面的代码,但我现在找不到。)

Do not switch the Optmistic Concurrency Updates off you will hide the problem and not fix it. 不要关闭Optmistic Concurrency Updates ,您将隐藏问题而不是修复它。 do the following: 请执行下列操作:

using (var db = new MyEntities())
{    
    using (var transaction = new TransactionScope())
    {
        var newGroup = new Groups
        {
            GroupDate = DateTime.Now,
            GroupName = "someName"
        };
        db.Groups.Add(newGroup);
        db.SaveChanges();
        transaction.Complete();
     }
}

The different now you are creating the TranscationScope inside the DBContext I hope this will solve your problem. 现在不同的是你在DBContext中创建TranscationScope我希望这能解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何计算存储的 DateTime.Now 和当前的 DateTime.Now 之间的差异? - How can i calculate the difference between a stored DateTime.Now and a current DateTime.Now? DbContext实体框架Datetime.Now字段 - DbContext Entity framework Datetime.Now fields 实体框架未声明datetime.now为null - Entity Framework not claiming datetime.now is null 为什么DateTime.Now和DateTime.UtcNow不是我当前的本地日期时间? - Why DateTime.Now and DateTime.UtcNow Isn't My Current Local DateTime? 为什么我需要创建一个返回 DateTime.Now 而不是直接使用 DateTime.Now 的 DateTime 服务? - Why do I need to create a DateTime service which returns DateTime.Now instead of using DateTime.Now directly? Oracle Entity Framework提供程序不会以毫秒为单位存储DateTime.Now - Oracle Entity Framework provider doesn't store DateTime.Now with milliseconds NSubstitute DateTime.Now() 如何让 DateTime.Now() 返回不断增加的日期和时间? - NSubstitute DateTime.Now() How can I get the DateTime.Now() to return an ever increasing date and time? 使用实体数据模型将DateTime.Now转换为SQLDatetime - DateTime.Now convert to SQLDatetime using Entity Data Model 如何比较DateTime.Now与MySQL DATETIME格式? - How can I compare DateTime.Now with MySQL DATETIME format? 实体框架无法使用datetime.now条件返回数据库中的记录 - entityframework can't return the records in database with datetime.now condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM