强制 Entity Framework 6 (EF6) 使用 nvarchar(MAX)

Force Entity Framework 6 (EF6) to use nvarchar(MAX)

我认为这很容易,但是...

如何强制 EF6 使用 nvarchar(MAX)

我试过:

[Column(TypeName = "nvarchar(MAX)")]

[Column(TypeName = "nvarchar")]
[MaxLength()]

modelBuilder.Entity<Date>().Property(o => o.test).HasColumnType("nvarchar(MAX)");

我正在使用 EF6.2.0 和 SQL2014 Express

如果您不指定长度,则 EF Code First 默认为 nvarchar(max),因此如果您指定名称列:

public string Name { get; set; }

您将获得一个 nvarchar(max) 列。

如果您需要指定长度,比如 100 个字符,那么您将在代码中指定列:

[MaxLength(50)]
public string Name { get; set; }

如果您需要指定 varchar 而不是 nvarchar,您可以使用:

[Column(TypeName = "VARCHAR")]
[MaxLength(50)]
public string Name { get; set; }

Code First Conventions, Code First Data Annotations and Column Annotations

您也可以将其默认设置为您需要的长度,而不是到处输入。 在 dbcontext class

中覆盖函数 OnModelCreating
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties()).Where(p => p.ClrType == typeof(string)))
    {
        if (property.GetMaxLength() == null)
        {
            property.SetMaxLength(256);
        }

        if (string.IsNullOrEmpty(property.GetColumnType()))
        {
            property.SetColumnType("varchar");
        }
    }
}

这就是 Entity Framework Core 5<

对我有用的东西
[Column(TypeName = "nvarchar(MAX)")]
[MaxLength(int.MaxValue)]
public string ImageBase64 { get; set; }

生成以下迁移:

migrationBuilder.AlterColumn<string>(
    name: "ImageBase64",
    table: "Medias",
    type: "nvarchar(MAX)",
    maxLength: 2147483647,
    nullable: true,
    oldClrType: typeof(string),
    oldType: "nvarchar(450)",
    oldMaxLength: 450,
    oldNullable: true);

MaxLength 是必需的,因为我们修改了 OnModelCreating 以避免对所有字符串列使用 nvarchar(MAX)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties())
        .Where(p => p.ClrType == typeof(string)))
    {
        if (property.GetMaxLength() == null)
            property.SetMaxLength(450);
    }