如何使用Sql Server解决EF 6中不受支持的DateTimeOffsets问题?
当我尝试实例化DbContext时,我收到此消息:
System.NotSupportedException:没有与原始类型“DateTimeOffset”的概念边类型“DateTimeOffset”对应的商店类型。
我在SQL Server上使用Entity Framework版本6。
DbContext
的构造DbContext
(带有抛出exception的行)如下所示:
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#代码中存在相关的数据类型。 关于为什么会这样,我有点失落。
这是我得到的堆栈跟踪:
System.Data.Entity.Entity.ModelConfiguration.Edm.Services上的System.Data.Entity.SqlServer.SqlProviderManifest.GetStoreType(TypeUsage edmType)中的System.Data.Entity.SqlServer.SqlProviderManifest.GetStorePrimitiveTypeIfPostSql9(String storeTypeName,String nameForException,PrimitiveTypeKind primitiveTypeKind) System.Data.Entity.ModelConfiguration.Edm.Services.PropertyMappingGenerator.Generate中的.StructuralTypeMappingGenerator.MapTableColumn(EdmProperty属性,String columnName,Boolean isInstancePropertyOnDerivedType)(EntityType entityType,IEnumerable
1 properties, EntitySetMapping entitySetMapping, MappingFragment entityTypeMappingFragment, IList
1 propertyPath,Boolean createNewColumn )在System.Data.Entity的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的System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)的System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest,DbProviderInfo providerInfo)上的Configuration.Edm.Services.DatabaseMappingGenerator.Generate(EdmModel conceptualModel) System.Data.Entity.Internal中的System.Data.Entity.Internal.LazyInternalContext.InitializeContext()处的System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput输入)中的.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()中的.InternalContext.ForceOSpaceLoadingForKnownEntityTypes()
我将不胜感激任何解决方法的想法,而不必破解数据类型。
捂脸! 此问题是由配置文件中连接字符串名称中的拼写错误引起的。
一旦我确定配置中的连接字符串的名称与提供给DbContext的连接字符串的名称匹配,问题就消失了。
当然,我没有被抛出的exception所帮助。
我在这里列出这个作为答案,以便将来的其他人可以找到这个答案,或者至少知道这种exception可以在各种情况下抛出。