簡體   English   中英

EF CodeFirst 設置默認字符串長度並用 DataAnnotations 覆蓋?

[英]EF CodeFirst set default string length and override with DataAnnotations?

我的大多數字符串列都設置在 50 左右。

除了將 DataAnnotation [StringLength(50)]添加到每個字符串屬性之外,我是否可以將默認字符串生成設置為 50,並且僅在需要與默認值不同時才指定 DataAnnotation?

例如

[StringLength(200)]
public string Thing1 { get; set; }
public string Thing2 { get; set; }
public string Thing3 { get; set; }
[MaxLength]
public string Thing4 { get; set; }

在這個例子中,Thing2 和 Thing3 默認可以是 varchar(50),而 Thing1 和 Thing2 會有所不同,因為我已經特別設置了它們。

許多實體和列,所以這不僅可以節省我的時間,而且可以讓我的實體類看起來更干凈

澄清(為了可能的重復問題): - 我不介意如何設置默認長度(FluentAPI 或其他任何東西) - 我確實介意如何設置覆蓋長度。 我想使用 DataAnnotations 覆蓋

您可以使用自定義代碼優先約定。 嘗試將此添加到您的上下文類中:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Properties<string>() 
                .Configure(c => c.HasMaxLength(500));
}

檢查此鏈接以獲取有關自定義代碼優先約定的更多信息

是的,您可以使用自定義代碼優先約定,但您還需要有一種方法將 nvarchar(max) 數據類型指定給字符串屬性。 所以,我想出了以下解決方案。

/// <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 MyDbContext : DbContext
{
    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; }
}

從 Entity Frameworks Core 6 開始,現在您可以覆蓋 ConfigureConventions DbContext,根據此站點設置給定屬性類型的默認配置

例子:

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
  {
     // Pre-convention model configuration goes here
     configurationBuilder.Properties<string>().HaveMaxLength(300);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM