Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C Datetime插入SQL Server值,精确到微秒_C#_Sql Server_Entity Framework_Datetime - Fatal编程技术网

C# C Datetime插入SQL Server值,精确到微秒

C# C Datetime插入SQL Server值,精确到微秒,c#,sql-server,entity-framework,datetime,C#,Sql Server,Entity Framework,Datetime,我在实体框架中使用.NETCore2.2。我需要在SQL Server中插入一些数据 在C中我使用DateTime数据类型,在SQL Server中我使用datetime26-默认值为:sysdatetime 例如,我的对象看起来像: public partial class Contact { public int Id { get; set; } public string Name { get; set; } public DateTime CreatedTim

我在实体框架中使用.NETCore2.2。我需要在SQL Server中插入一些数据

在C中我使用DateTime数据类型,在SQL Server中我使用datetime26-默认值为:sysdatetime

例如,我的对象看起来像:

public partial class Contact
{
    public int Id { get; set; } 
    public string Name { get; set; } 
    public DateTime CreatedTime { get; set; } 
}
如果我在创建对象时将CreatedTime保留为null,并让SQL Server使用默认的sysdatetime,我将在数据库中获得类似于:2020-05-19 09:31:12.383593的内容

据我所知,DateTime数据类型本身已经具有微秒精度,但是,如果我为该CreatedTime属性设置了一个值,例如:

obj.CreatedTime = DateTime.Now.AddTicks(123);
Console.WriteLine(obj.CreatedTime.ToString("yyyy-MM-dd HH:mm:ss.ffffff"));
我可以在控制台中看到值,它将是2020-08-18 07:42:52.131102。但是当通过EntityFramwork插入obj时,数据库中的值将仅为毫秒:2020-08-18 07:42:52.131000。看起来EntityFramework只是以毫秒的精度传递日期时间


非常感谢您的支持。

您可能需要强制EF使用精度为100ns的SQL Server DateTime27 max/default数据类型YYYY-MM-DD hh:MM:ss.0000000,您可以通过以下几种方式执行此操作

全球


您需要使用DateTime2 datetype modelBuilder.Properties.Configurec=>c.HasColumnTypedatetime2;或modelBuilder.Entity.Propertyf=>f.SomeDate.HasColumnTypedatetime2;请分享一个。我猜,在某个地方,EF一定在推断SQL数据类型,但它弄错了。您可能希望使用数据批注:[ColumnTypeName=DateTime26],即使声明在针对SQL Server时DateTime的默认映射是DateTime27,谢谢大家!我真的很感谢你的帮助@迈克尔·兰德尔非常感谢你解决了我的问题!你能把它作为答案贴出来吗?我会给它标上正确答案的@CordCaster——是的,但是如果他需要一个比DB在日期时间格式更精确的值,那就值得思考,也许他不在这里,如果DATETME2会覆盖它,那就好了,这是我之前必须考虑的事情。
modelBuilder
  .Properties<DateTime>()
  .Configure(c => c.HasColumnType("datetime2"));
modelBuilder
  .Entity<SomeEntiity>()
  .Property(f => f.SomeDate)
  .HasColumnType("datetime2"); 
[Column(TypeName = "DateTime2(7)")]