Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将EF6 Code First字符串流利地设置为nvarchar(最大值)_C#_Entity Framework_Ef Code First_Ef Fluent Api - Fatal编程技术网

C# 将EF6 Code First字符串流利地设置为nvarchar(最大值)

C# 将EF6 Code First字符串流利地设置为nvarchar(最大值),c#,entity-framework,ef-code-first,ef-fluent-api,C#,Entity Framework,Ef Code First,Ef Fluent Api,我正在使用fluentapi构建一个EF6代码优先模型。我的理解是,默认情况下,字符串将是nvarchar(max),这(直截了当地说)对于默认值来说是哑的。因此,我添加了以下约定代码,将最大默认长度设置为255个字符: modelBuilder.Properties<string>() .Configure(p => p.HasMaxLength(255)); 我想将其应用于我实际希望成为NVARCHAR(MAX)的特定字符串属性 我应该在fluent API中添加

我正在使用fluentapi构建一个EF6代码优先模型。我的理解是,默认情况下,字符串将是
nvarchar(max)
,这(直截了当地说)对于默认值来说是哑的。因此,我添加了以下约定代码,将最大默认长度设置为255个字符:

modelBuilder.Properties<string>()
    .Configure(p => p.HasMaxLength(255));
我想将其应用于我实际希望成为
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(?????));
Property(x => x.MyVarcharMaxProperty)
    .HasColumnType("nvarchar(max)");
modelBuilder.Properties()
.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)"));
modelBuilder.Properties()
.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
类中执行此操作,则类似于@RickNo的答案,但执行方式如下:

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

有一种方法指示您使用数据库允许的最大值

IsMaxLength()

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

您可以使用HasColumnType

也可以不使用任何HasColumnType或HasMaxLength。 无需使用HasMaxLength

使用实际nvarchar(最大)长度限制是否错误?2^30-1