2016-06-16 97 views
0

現狀:EF6設置的MaxLength

我有一個基類查找,如下:

public abstract class Lookup : DeactivatableDomainModel { 
    [Required] 
    [Key] 
    public int ID { get; set; } 

    [Required] 
    public string Description { get; set; } 

    [Required] 
    public int DisplayOrder { get; set; } 
    } 

我還創建了一個屬性IsLookup

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] 
public class IsLookup : Attribute { 
    public int DescriptionLength { get; set; } 
    public int CodeLength { get; set; } 

    public IsLookup(int DescriptionLength, int CodeLength = 0) { 
    this.DescriptionLength = DescriptionLength; 
    this.CodeLength = CodeLength; 
    } 
} 

我們的目標是能夠創建以下聲明:

[IsLookup(40)] 
public class TestCategory : Lookup { } 

...並使用OnModelCreating財產描述的MaxLength設置爲40

我已經能夠代碼的東西,看起來像它應該工作,以及add-migration運行得很好,但所得到的遷移不具有最大長度集:

protected override void OnModelCreating(DbModelBuilder modelBuilder) { 
    base.OnModelCreating(modelBuilder); 

    modelBuilder.Properties() 
     .Where(p => p.Name == "Description" && p.DeclaringType.GetCustomAttributes(false).OfType<IsLookup>().FirstOrDefault() != null) 
     .Configure(
     c => c.HasMaxLength(((IsLookup)c.ClrPropertyInfo.DeclaringType.GetCustomAttributes(typeof(IsLookup), false).FirstOrDefault()).DescriptionLength) 
    ); 

    } 

結果是:

CreateTable(
     "Lookups.TestCategories", 
     c => new { 
     ID = c.Int(nullable: false, identity: true), 
     Description = c.String(nullable: false), 
     DisplayOrder = c.Int(nullable: false), 
     Active = c.Boolean(nullable: false), 
     RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), 
     }) 
     .PrimaryKey(t => t.ID); 

因此,問題是......爲什麼說明沒有在遷移代碼中設置其長度?這甚至有可能嗎?

<gripe>如果有一種方法可以調試add-migration,這會容易得多。 </gripe>

+0

我知道這很煩人質疑的理由......但是,爲什麼你需要指定的類級屬性的長度?爲什麼不把你的任意長度放在代碼和描述字段上,並且在類上有一個IsLookup屬性,這個屬性不會花費太多時間?您始終可以使用反射來從屬性上的屬性中獲取長度。 – siride

+0

很好 - 我做了一些工作。目的是構建40或50個查找,每個查找具有不同的描述字段長度。最大長度驅動代碼生成進行驗證,否則我只需將長度設置爲250即可完成驗證。 –

回答

0

我敢肯定,​​會給你在該財產被宣佈,在您的示例Lookup類是在Description屬性聲明的類型。由於Lookup不具有IsLookup屬性,因此沒有設置。嘗試通過註冊類型看第一則設置說明欄你會發現後:

modelBuilder.Types() 
    .Where(t => t.IsSubclassOf(typeof(Lookup))) 
    .Having(x => x.GetCustomAttributes(false).OfType<IsLookup>().FirstOrDefault()) 
    .Configure((config, att) => { 
     config.Property("Description").HasMaxLength(att.DescriptionLength); 
    }); 
+0

你,先生,是個天才!我從錯誤的方向追求它。我也不知道方法'IsSubclassOf()'。不夠感謝你! –

相關問題