![](/img/trans.png)
[英]EF Code First - Globally set varchar mapping over nvarchar
[英]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>
類中執行此操作,則它類似於@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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.