【问题标题】:Setting MaxLength for all strings in Entity Framework code first首先为实体框架代码中的所有字符串设置 MaxLength
【发布时间】:2014-01-14 14:16:46
【问题描述】:

我正在使用 Entity Framework 6 开发代码优先数据库。

我知道我可以在模型的属性上设置[MaxLength(myLen)]

我想知道的是,是否可以在过滤器或自定义属性中执行此操作,以便所有字符串都采用默认值,例如 250,除非直接在属性上指定。

如果做不到这一点,有没有办法改变nvarchar(max)的默认值?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework ef-code-first


    【解决方案1】:

    Entity Framework 在 6.1 中为此引入了 Custom Code First Conventions

    modelBuilder.Properties<string>()
                .Configure(c => c.HasMaxLength(250));
    

    约定以最后胜利的方式运行,Fluent API 和数据注释可用于在特定情况下覆盖约定

    【讨论】:

    • 准确,谢谢。我只选择了另一个作为答案,因为他是第一个 :) 谢谢。链接也很棒 - 刚刚保存了那个。
    【解决方案2】:

    您可以这样做,确保所有字符串都是数据库提供程序支持的最大长度:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Properties<string>().Configure(p => p.IsMaxLength());
        }
    

    在您的DbContext 类中添加此方法(或修改现有方法)。

    【讨论】:

    • 太棒了!正是我所追求的 :) 我还看到,如果我将 MaxLength 放在属性上,那么它会覆盖 modelBuilder - 完美。 (当它允许我时会接受答案..)
    • 顺便说一下,我使用了 MaxLength - 而不是 IsMaxLength;可能值得为未来的用户进行调整:)
    【解决方案3】:

    在 EF6 中,您可以使用自定义代码优先约定,但您还需要有一种方法可以将 nvarchar(max) 数据类型指定给字符串属性。所以,我想出了以下解决方案。 另见: https://msdn.microsoft.com/en-us/data/jj819164#order

    /// <summary>
    /// Set this attribute to string property to have nvarchar(max) type for db table column.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public sealed class TextAttribute : Attribute
    {
    }
    
    /// <summary>
    /// Changes all string properties without System.ComponentModel.DataAnnotations.StringLength or
    /// Text attributes to use string length 16 (i.e nvarchar(16) instead of nvarchar(max) by default).
    /// Use TextAttribute to a property to have nvarchar(max) data type.
    /// </summary>
    public class StringLength16Convention : Convention
    {
        public StringLength16Convention()
        {
            Properties<string>()
                .Where(p => !p.GetCustomAttributes(false).OfType<DatabaseGeneratedAttribute>().Any())
                .Configure(p => p.HasMaxLength(16));
    
            Properties()
                .Where(p => p.GetCustomAttributes(false).OfType<TextAttribute>().Any())
                .Configure(p => p.IsMaxLength());
        }
    }
    
    public class CoreContext : DbContext, ICoreContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Change string length default behavior.
            modelBuilder.Conventions.Add(new StringLength16Convention());
        }
    }
    
    
    public class LogMessage
    {
        [Key]
        public Guid Id { get; set; }
    
    
        [StringLength(25)] // Explicit data length. Result data type is nvarchar(25)
        public string Computer { get; set; }
    
        //[StringLength(25)] // Implicit data length. Result data type is nvarchar(16)
        public string AgencyName { get; set; }
    
        [Text] // Explicit max data length. Result data type is nvarchar(max)
        public string Message { get; set; }
    }
    

    【讨论】:

      【解决方案4】:

      在此代码中,ModelBuilder 类定义实体的形状、它们之间的关系以及它们如何映射到数据库。

      public class WebsiteDBContext : DbContext
      {
      
          public WebsiteDBContext(DbContextOptions<WebsiteDBContext> options) : base(options)
          {
          }
      
          public DbSet<Global> Globals { get; set; }
      
          protected override void OnModelCreating(ModelBuilder builder)
          {
              // it should be placed here, otherwise it will rewrite the following settings!
              base.OnModelCreating(builder);
      
              builder.Entity<Global>();
              builder.Entity<Global>(entity =>
              {
                  entity.Property(global => global.MainTopic).HasMaxLength(150).IsRequired();
                  entity.Property(global => global.SubTopic).HasMaxLength(300).IsRequired(false);
                  entity.Property(global => global.Subject).IsRequired(false);
                  entity.Property(global => global.URL).HasMaxLength(150).IsRequired(false);
              });
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-23
        • 1970-01-01
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-11
        • 1970-01-01
        相关资源
        最近更新 更多