EF CodeFirst设置默认字符串长度并覆盖DataAnnotations
本文关键字:覆盖 DataAnnotations 字符串 CodeFirst 设置 默认 EF | 更新日期: 2023-09-27 18:11:42
我将大多数字符串列设置在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);
}