【问题标题】:How can I globally set the store type for TimeSpan properties in EF?如何在 EF 中全局设置 TimeSpan 属性的存储类型?
【发布时间】:2012-05-30 11:00:35
【问题描述】:

我有一个DbContext 类,它在OnModelCreating 期间向模型构建器添加各种实体配置。此上下文在针对 SQL Server 运行时效果很好,但在针对 SQL CE 时失败,因为某些实体包含 TimeSpan 属性。

当数据库是 SQL CE 时,是否可以在 OnModelCreating 期间修改配置以将存储类型设置为适当的值(例如 nvarchar(30))?

在我的主应用程序中,我有一个 DbContext,如下所示:

public class MyDbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new Entity1Config());
        modelBuilder.Configurations.Add(new Entity2Config());
        modelBuilder.Configurations.Add(new Entity3Config());
        // Lots more entity and complex type configurations here.
    }
}

DbContext 针对完整的 SQL Server 运行。在我的测试中,我想针对 SQL CE 而不是 SQL Server Express 运行。理想情况下,我想用约定或显式覆盖来覆盖有问题的配置,如下所示:

public class MyTestingDbContext : MyDbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Entity1>()     
            .Property(x => x.Duration)     
            .HasColumnType("nvarchar(30) not null");
    }
}

明确地说,我只对不涉及直接修改原始 DbContext 类或其实体的解决方案感兴趣。


注意:ModelBuilder 中似乎有一个约定,它已经对MaxLength 属性进行了特定于 SQL CE 的处理,但它主要是使用内部类实现的。 (嘘!)

【问题讨论】:

  • SQL CE 只支持 nvarchar,不支持 varchar
  • 我正在做同样的事情,但目前我有属性可以在处理程序上应用类型。当我尝试覆盖属性时,我收到一条消息Conflicting configuration settings were specified for column 'MyColumn' on table 'MyTable',这很有意义,但能够覆盖它会非常有用。
  • @glenatron 我已经重新使用 SQL Server 2012 的 LocalDB 而不是 SQL CE。我所有的问题都消失了!

标签: entity-framework ef-code-first sql-server-ce entity-framework-4.3


【解决方案1】:

您可以通过 Fluent Interface 进行配置,调用 DateTimePropertyConfiguration.HasColumnType Method

        modelBuilder.Entity<MyEntity>()
            .Property(x=> x.Duration)
            .HasColumnType("Varchar(30) NOT NULL");

或通过ColumnAttribute.DbType property

【讨论】:

  • 谢谢,但这不能满足我的需要。我会让我的问题更相关 - 你让我意识到我错过了一些重要的事情。
猜你喜欢
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 2013-10-09
  • 2021-12-31
  • 1970-01-01
相关资源
最近更新 更多