我正在使用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
或将它们转换为{{ 1}?
测试的目的是确保从数据层到界面的所有内容都按预期工作,因此如果有更好的方法来实现这种可能提供有用替代方案的测试。
答案 0 :(得分:3)
使用SQL Server 2012 LocalDB而不是CE可能会更好。我意识到使用SQL Server 2012可能会引入潜在的兼容性问题(虽然它确实不应该),但LocalDB是一个完整的SQL-Server功能基于文件的数据库。它支持datetime2
答案 1 :(得分:1)
最后,我找到了一个解决这个问题的解决方案,该解决方案适用于我正在使用的端到端测试配置。我采用的解决方案是使用特殊的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崩溃。