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

时间:2015-03-11 16:32:04

标签: c# .net entity-framework-6 datetimeoffset

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

  

System.NotSupportedException:没有与概念方类型相对应的商店类型' DateTimeOffset'原始类型' DateTimeOffset'。

我在SQL Server上使用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; }
}

数据库迁移运行正常并生成如下表:

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)      在System.Data.Entity.SqlServer.SqlProviderManifest.GetStoreType(TypeUsage edmType)      在System.Data.Entity.ModelConfiguration.Edm.Services.StructuralTypeMappingGenerator.MapTableColumn(EdmProperty属性,String columnName,Boolean isInstancePropertyOnDerivedType)      at System.Data.Entity.ModelConfiguration.Edm.Services.PropertyMappingGenerator.Generate(EntityType entityType,IEnumerable 1 properties, EntitySetMapping entitySetMapping, MappingFragment entityTypeMappingFragment, IList 1 propertyPath,Boolean createNewColumn)      在System.Data.Entity.ModelConfiguration.Edm.Services.TableMappingGenerator.Generate(EntityType entityType,DbDatabaseMapping databaseMapping)      在System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.GenerateEntityTypes(DbDatabaseMapping databaseMapping)      在System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.Generate(EdmModel conceptualModel)      在System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest,DbProviderInfo providerInfo)      在System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)      在System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)      在System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput输入)      在System.Data.Entity.Internal.LazyInternalContext.InitializeContext()      在System.Data.Entity.Internal.InternalContext.ForceOSpaceLoadingForKnownEntityTypes()      在System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()

如果有任何方法可以解决这个问题,我将不胜感激,而不必破解数据类型。

1 个答案:

答案 0 :(得分:6)

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

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

当然,我没有被抛出的例外所帮助。

我在这里列出这个作为答案,以便将来的其他人可能会找到这个答案,或者至少知道在各种情况下都会抛出这种异常。