如何使用 Sql 服务器解决 EF 6 中不受支持的 DateTimeOffsets 问题?

How do I resolve issues with unsupported DateTimeOffsets in EF 6 using Sql Server?

当我尝试实例化 DbContext 时收到此消息:

System.NotSupportedException: There is no store type corresponding to the conceptual side type 'DateTimeOffset' of primitive type 'DateTimeOffset'.

我在 SQL 服务器上使用 Entity Framework 版本 6。

DbContext 的构造函数(带有抛出异常的行)如下所示:

    internal TestHubContext(string connectionStringName) : base(connectionStringName)
    {
        var objectContext = (this as IObjectContextAdapter).ObjectContext;

        ...
    }

实体是使用代码优先创建的,如下所示:

public class Order
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public System.Guid Id { get; set; }

    [MaxLength(60)]
    [Required]
    public string CreatedBy { get; set; }

    [Required]
    public System.DateTimeOffset CreatedUtcDate { get; set; }
}

数据库迁移 运行 正常并生成了一个 table 像这样:

CREATE TABLE [dbo].[Orders](
[Id] [uniqueidentifier] NOT NULL,   
[CreatedBy] [nvarchar](60) NOT NULL,
[CreatedUtcDate] [datetimeoffset](7) NOT NULL,  

所以相关的数据类型存在于数据库和C#代码中。我有点不知道为什么会这样。

这是我得到的堆栈跟踪:

at System.Data.Entity.SqlServer.SqlProviderManifest.GetStorePrimitiveTypeIfPostSql9(String storeTypeName, String nameForException, PrimitiveTypeKind primitiveTypeKind) at System.Data.Entity.SqlServer.SqlProviderManifest.GetStoreType(TypeUsage edmType) at System.Data.Entity.ModelConfiguration.Edm.Services.StructuralTypeMappingGenerator.MapTableColumn(EdmProperty property, String columnName, Boolean isInstancePropertyOnDerivedType) at System.Data.Entity.ModelConfiguration.Edm.Services.PropertyMappingGenerator.Generate(EntityType entityType, IEnumerable1 properties, EntitySetMapping entitySetMapping, MappingFragment entityTypeMappingFragment, IList1 propertyPath, Boolean createNewColumn) at System.Data.Entity.ModelConfiguration.Edm.Services.TableMappingGenerator.Generate(EntityType entityType, DbDatabaseMapping databaseMapping) at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.GenerateEntityTypes(DbDatabaseMapping databaseMapping) at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.Generate(EdmModel conceptualModel) at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.InternalContext.ForceOSpaceLoadingForKnownEntityTypes() at System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()

如果有任何解决此问题的想法,我将不胜感激,而无需修改数据类型。

捂脸! 此问题是由配置文件中的连接字符串名称拼写错误引起的。

一旦我确定配置中的连接字符串名称与提供给 DbContext 的名称匹配,问题就消失了。

当然,抛出的异常对我没有任何帮助。

我将此列为答案,以便将来其他人可能会找到此答案,或者至少知道在各种情况下都可能引发此类异常。