Jer*_*acs 14 c# entity-framework ef-code-first ef-fluent-api
我正在使用流畅的API构建EF6代码第一个模型.我的理解是,默认情况下,字符串将是nvarchar(max),对于默认值,它(直言不讳)是愚蠢的.所以我添加了以下约定代码来将max default length设置为255个字符:
        modelBuilder.Properties<string>()
            .Configure(p => p.HasMaxLength(255));
然后我创建了一个像这样的装饰器:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class TextAttribute : Attribute
{
}
我想将此应用于我实际想要成为NVARCHAR(MAX)的特定字符串属性.
我应该在流畅的API中放置什么来确保使用[Text]装饰器的所有字符串属性都是在带有NVARCHAR(MAX)的数据库中构建的?我假设它会是这样的:
        modelBuilder.Properties<string>()
            .Where(p => p.CustomAttributes.Any(a => typeof(TextAttribute).IsAssignableFrom(a.AttributeType)))
            .Configure(p => p.HasMaxLength(?????));
或者我这样做完全错了?
Ric*_*kNo 19
我不知道你现在是否找到了答案,但是如果其他人想知道怎么做,只需设置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)).
Cha*_*ian 10
如果你在EntityTypeConfiguration<MyEntity>课堂上这样做,它类似于@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());
| 归档时间: | 
 | 
| 查看次数: | 11778 次 | 
| 最近记录: |