【问题标题】:Allow Entity Framework 4.5 to use datetime2 with SQL Server CE4允许 Entity Framework 4.5 将 datetime2 与 SQL Server CE4 一起使用
【发布时间】:2012-10-04 14:49:17
【问题描述】:

我正在使用 SQL Server 2008 开发实体框架项目。我们最近更改为对很多日期使用 datetime2 字段类型,因为我们需要精度。

这适用于我们的实时和开发数据库,​​但作为我们端到端测试的一部分,我们一直在使用 SQL Server CE 4.0,它不支持 datetime2 类型。当 Entity Framework 尝试构建数据库时,它会返回一系列异常,如下所示:

error 0040: The Type datetime2 is not qualified with a namespace or alias. Only primitive types can be used without qualification.

显然,为了测试目的而更改我们的生产代码没有任何价值,那么有没有办法告诉它将datetime2 值转换为常规datetime 或将它们转换为varchar

测试的目的是确保从数据层到接口的所有内容都按预期工作,因此如果有更好的方法来实现这种测试,可能会提供有用的替代方案。

【问题讨论】:

    标签: entity-framework-4 sql-server-ce-4 automated-tests datetime2


    【解决方案1】:

    您最好使用 SQL Server 2012 LocalDB 而不是 CE。我意识到使用 SQL Server 2012 可能会引入潜在的兼容性问题(尽管它确实不应该),但 LocalDB 是一个完整的 SQL-Server 功能基于文件的数据库。支持datetime2

    【讨论】:

    • 好主意。由于实体框架正在与数据库进行所有对话,因此它可能应该相当兼容。没有升级到最新版本的 .net/Visual Studio 就可以与 LocalDB 交谈吗?
    • @glenatron - 是的,它只需要安装正确的客户端。
    • .NET 4.0.3 是必需的,而不是 4.5
    【解决方案2】:

    最后,我找到了一个足以解决我正在使用的端到端测试配置的问题的解决方案。我采用的解决方案是使用特殊的 DataContext 来处理 Sql Server CE 请求,因此:

    public class TestDataContext : DataContext 
    {
    
        protected override void  OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            // list of available Conventions: http://msdn.microsoft.com/en-us/library/system.data.entity.modelconfiguration.conventions(v=vs.103).aspx 
    
            // Remove the column attributes that cause the datetime2 errors, so that 
            // for SQL Server CE we just have regular DateTime objects rather than using
            // the attribute value from the entity.
            modelBuilder.Conventions.Remove<ColumnAttributeConvention>();
    
            // Attempt to add back the String Length restrictions on the entities. I havent 
            // tested that this works.
            modelBuilder.Configurations.Add( new ComplexTypeConfiguration<StringLengthAttributeConvention>());
    
            // SQL Server CE is very sensitive to potential circular cascade deletion problems
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    
        }
    
    }
    

    通过在我的测试类中用 TestDataContext 替换常规 DataContext,我有相同的行为,而不会导致 SQL Server CE 崩溃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多