我正在開發一個代碼優先數據庫,使用實體框架6.在實體框架代碼首先
所有字符串MAXLENGTH設置我知道我可以在模型的屬性設置[MaxLength(myLen)]
。
我想知道的是,如果可以在過濾器或自定義屬性中執行此操作,以便所有字符串都採用默認值(例如250),除非直接在屬性上指定。
沒有這個,有沒有辦法改變nvarchar(max)
的默認值?
我正在開發一個代碼優先數據庫,使用實體框架6.在實體框架代碼首先
所有字符串MAXLENGTH設置我知道我可以在模型的屬性設置[MaxLength(myLen)]
。
我想知道的是,如果可以在過濾器或自定義屬性中執行此操作,以便所有字符串都採用默認值(例如250),除非直接在屬性上指定。
沒有這個,有沒有辦法改變nvarchar(max)
的默認值?
你可以做到這一點,確保所有的字符串都是由數據庫供應商支持的最大長度:在你DbContext
類
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<string>().Configure(p => p.IsMaxLength());
}
添加這個方法(或修改現有的一個)。
實體框架6.1的推出Custom Code First Conventions此
modelBuilder.Properties<string>()
.Configure(c => c.HasMaxLength(250));
約定在最後的獲勝方式操作和流利的API和數據註解可用於在特定情況下
現貨,謝謝。我只選擇另一個作爲他的第一個答案:)但是,謝謝你。偉大的鏈接 - 只保存了一個。 – Darren
在EF6您覆蓋公約可以使用自定義代碼的第一個約定,但是您還需要有一種方法來將nvarchar(max)數據類型指定爲字符串屬性。所以,我想出了以下解決方案。 另見: https://msdn.microsoft.com/en-us/data/jj819164#order
/// <summary>
/// Set this attribute to string property to have nvarchar(max) type for db table column.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class TextAttribute : Attribute
{
}
/// <summary>
/// Changes all string properties without System.ComponentModel.DataAnnotations.StringLength or
/// Text attributes to use string length 16 (i.e nvarchar(16) instead of nvarchar(max) by default).
/// Use TextAttribute to a property to have nvarchar(max) data type.
/// </summary>
public class StringLength16Convention : Convention
{
public StringLength16Convention()
{
Properties<string>()
.Where(p => !p.GetCustomAttributes(false).OfType<DatabaseGeneratedAttribute>().Any())
.Configure(p => p.HasMaxLength(16));
Properties()
.Where(p => p.GetCustomAttributes(false).OfType<TextAttribute>().Any())
.Configure(p => p.IsMaxLength());
}
}
public class CoreContext : DbContext, ICoreContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Change string length default behavior.
modelBuilder.Conventions.Add(new StringLength16Convention());
}
}
public class LogMessage
{
[Key]
public Guid Id { get; set; }
[StringLength(25)] // Explicit data length. Result data type is nvarchar(25)
public string Computer { get; set; }
//[StringLength(25)] // Implicit data length. Result data type is nvarchar(16)
public string AgencyName { get; set; }
[Text] // Explicit max data length. Result data type is nvarchar(max)
public string Message { get; set; }
}
好極了!正是我之後:)我也看到,如果我把'MaxLength'放在一個屬性上,這會覆蓋'modelBuilder' - 完美。 (接受答案,當它讓我..) – Darren
順便說一句,我用MaxLength - 不是IsMaxLength;可能值得爲未來的用戶調整:) – Darren