【问题标题】:How to use sql user defined types in entity framework 6如何在实体框架6中使用sql用户定义类型
【发布时间】:2017-01-07 01:24:04
【问题描述】:

如何在实体框架中使用由 SQL CLR 编写的用户定义类型? 此类型旨在以正确的方式实现波斯日期数据类型。 我尝试使用 HasColumnType() 来使用这个自定义类型:

modelBuilder.Properties()
            .Where(x => x.PropertyType == typeof(DateTime))
            .Configure(c => c.HasColumnType("PersianDate"));

但它不成功,我收到了这个错误:

System.InvalidOperationException:序列不包含匹配元素 在 System.Linq.Enumerable.Single[TSource](IEnumerable1 source, Func2 谓词) 在 System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest,字符串名称) 在 System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty 列,EntityType 表,DbProviderManifest providerManifest) 在 System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty 列,EntityType 表,DbProviderManifest providerManifest,布尔allowOverride,布尔fillFromExistingConfiguration) 在 ...

我确定这个错误是使用 HasColumnType() 的结果。此外,我确信这种类型在我的数据库中可以正常工作。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework sqlclr


    【解决方案1】:

    此时,我也同意您在 HasColumnType("PersianDate") 中声明了错误的值。

    基于 MSDN,HasColumnType 配置数据库列的数据类型,通常为原始数据类型(更多信息请参阅here)。

    EF 6 的当前实现可能对用户定义的数据类型有一些限制,因为用户定义的类型需要在初始化 DB 时检查该类型尚未创建的例程。

    作为用户定义类型的解决方法,在 SQL 端使用 datetime2 将波斯日期声明为列(datetime 的最小限制为 1753 年 1 月 1 日,因此不适用于波斯年份)并映射它作为DateTime:

    modelBuilder.Properties()
                .Where(x => x.PropertyType == typeof(DateTime))
                .Configure(c => c.HasColumnType("datetime2"));
    

    欢迎提出任何建议。

    其他参考:https://stackoverflow.com/a/8143626/6378815

    【讨论】:

    • 可能你是对的,它只是使用原始类型。请注意,在构建任何与 DateTime 相关的迁移之前,我在我的数据库中添加了这个自定义类型。 datetime2 也有一些限制,我不想使用它,其中之一是可能在数据库中插入错误的日期。
    • @Tetsuya Yamamoto 非常感谢你节省了我的时间
    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    相关资源
    最近更新 更多