实体框架4将DateTimeOffset映射到Visual Studio 2010中的SQL日期时间

Car*_*lis 4 entity-framework datetimeoffset visual-studio-2010

我正在使用带有.NET/Entity Framework 4 RTM的Visual Studio 2010 RTM和模型驱动的设计方法.当我使用DateTimeOffset字段创建实体时,EF建模器会尝试将DateTimeOffset映射到SQL日期时间而不是SQL datetimeoffset.我正在使用SQL Server 2008 Express,因此数据库中支持datetimeoffset.

Visual Studio出现此错误:

2019年错误:指定的成员映射无效.类型'Data.SqlStorage.MyType'中成员'Created'的类型'Edm.DateTimeOffset [Nullable = False,DefaultValue =,Precision =]'与'SqlServer.datetime不兼容[Nullable = False,DefaultValue =,Precision = 3]'成员'创建'类型'Data.SqlStorage.Store.MyTypes

如果我直接在EDMX StorageModels xml部分编辑类型,我会收到以下错误:

错误40:类型datetimeoffset未使用命名空间或别名限定.只有PrimitiveTypes可以无限制地使用.

为什么建模者没有正确地将其映射到SQL datetimeoffset类型?当我还在使用Visual Studio 2010和.NET framework 4的beta版本时,也会出现此问题.

bka*_*aid 5

在RTM版本中,您可以在DbContext中执行以下操作:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) {
     modelBuilder.Entity<EntityName>().Property(p => p.PropertyName).HasColumnType("datetimeoffset");
 }
Run Code Online (Sandbox Code Playgroud)

这对于告知Entity Framework Code First在生成数据库时使用datetime2而不是datetime也很有用.