【问题标题】:Entity Framework 4.1 code first approach: how to define length of propertiesEntity Framework 4.1 代码优先方法:如何定义属性长度
【发布时间】:2011-08-06 09:32:57
【问题描述】:

顾名思义:

如何以代码优先的方法告诉 Entity Framework 4.1,我确实希望某些属性(特别是字符串类型)的长度为 256,或 nvarchar(max),或...

如果这是例如我的模型

public class Book{
   public string Title { get; set; } //should be 256 chars
   public string Description {get;set} //should be nvarchar(max)
}

如何定义?

提前致谢!

【问题讨论】:

标签: mapping ef-code-first entity-framework-4.1


【解决方案1】:

您可以使用以下方式 如果你想要一个最大字符串长度

[StringLength(Int32.MaxValue)]

或者

[MaxLength]

或者

Property(m => m.Title ).IsRequired().HasMaxLength(128);

或者

[MaxLength(256)]

【讨论】:

    【解决方案2】:

    正如我在评论中所说,这很简单。
    只需使用来自DataAnnotation[StringLength(1000)][MaxLength]

    【讨论】:

      【解决方案3】:

      在 EF4.1 RTW 中,SQL Server 的默认长度为 nvarchar(max),SQL CE 的默认长度为 nvarchar(4000)。要更改长度,请使用StringLengthMaxLength 注释或流畅映射HasMaxLength

      [StringLength(256)]
      public string Title { get; set; }
      

      或者

      [MaxLength(256)]
      public string Title { get; set; }
      

      或者

      modelBuilder.Entity<Book>()
                  .Property(p => p.Title)
                  .HasMaxLength(256);
      

      【讨论】:

      • 嗯!您能否解释一下为什么 SQL Server 2008 R2 默认为任何字符串属性创建 nvarchar(128)(而不是您所说的 nvarchar(max))?
      • 因为您使用的是 RC 而不是最新的 RTW 最终版本。
      • [StringLength] 仅用于验证目的,不用作数据库约束。
      • @Jalal - 你能详细说明那条评论吗?
      • @Jalal @Pasi Savolainen 我将[StringLength(50)] 添加到一个属性中。使用 EF6 RC1 并将其放入我的迁移中:AlterColumn("dbo.Properties", "OrganisationsReference", c =&gt; c.String(maxLength: 50));
      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 2016-11-03
      • 1970-01-01
      • 2013-03-26
      • 2011-12-06
      • 1970-01-01
      • 2013-06-13
      • 2012-08-22
      相关资源
      最近更新 更多