将 EF6 Code First 字符串流畅地设置为 nvarchar(max)

Set EF6 Code First strings fluently to nvarchar(max)

我正在使用 Fluent API 构建 EF6 代码优先模型。我的理解是,默认情况下,字符串将为 nvarchar(max),这(直言不讳)对于默认值来说是愚蠢的。所以我添加了以下约定代码以将最大默认长度设置为 255 个字符:

modelBuilder.Properties<string>()
    .Configure(p => p.HasMaxLength(255));

然后我像这样创建了一个装饰器:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class TextAttribute : Attribute
{
}

我想将其应用于我实际想要的特定字符串属性 NVARCHAR(MAX)

我应该在 fluent API 中输入什么来确保所有带有 [Text] 装饰器的字符串属性都内置在带有 NVARCHAR(MAX) 的数据库中?我假设它会是这样的:

modelBuilder.Properties<string>()
    .Where(p => p.CustomAttributes.Any(a => typeof(TextAttribute).IsAssignableFrom(a.AttributeType)))
    .Configure(p => p.HasMaxLength(?????));

还是我这样做完全错了?

我不知道您现在是否找到了答案,但如果其他人想知道如何去做,只需设置 SQL 数据类型并忽略 HasMaxLength() 调用。

        modelBuilder.Properties<string>()
            .Where(p => p.CustomAttributes.Any(a => typeof(TextAttribute).IsAssignableFrom(a.AttributeType)))
            .Configure(p => p.HasColumnType("nvarchar(max)"));

使用 IsMaxLength() 或 HasMaxLength(null) 会将字段设置为 nvarchar(4000)(如果将数据类型指定为 varchar,则为 varchar(8000))。

如果您在 EntityTypeConfiguration<MyEntity> class 中执行此操作,它类似于 @RickNo 的回答,但这样做是这样的:

Property(x => x.MyVarcharMaxProperty)
    .HasColumnType("nvarchar(max)");

有一种方法表明您使用了数据库允许的最大值。

IsMaxLength()

    modelBuilder.Properties<string>()
        .Where(p => p.CustomAttributes.Any(a => typeof(TextAttribute).IsAssignableFrom(a.AttributeType)))
        .Configure(p => p.HasColumnType("nvarchar").IsMaxLength());

您可以使用 HasColumnType

或者您可以在没有任何 HasColumnType 或 HasMaxLength 的情况下使用。 不需要使用HasMaxLength