2016-06-16 8 views
0

次のように私は、基底クラス検索を持ってEF6セットのMaxLength状況

:私も属性IsLookupを作成しました

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

[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 { } 

...と私はそれが動作するはずのように見える何かをコーディングすることができました、そしてadd-migration実行だけで罰金40

にプロパティの説明のMaxLengthを設定するOnModelCreatingを使用しますが、

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); 
結果の移行がMAXLENGTHが設定されていません。

なぜ、説明の長さが移行コードに設定されていないのですか?これも可能ですか?

<gripe>add-migrationをデバッグする方法があれば、はるかに簡単です。 </gripe>

+0

私はそれが根拠に疑問を感じるのは分かっていますが、どうしてクラスレベルの属性で長さを指定する必要があるのですか? ?なぜコードや説明フィールドに任意の長さを置くだけで、長さを取らないクラスにIsLookup属性があるのでしょうか?リフレクションを使用してプロパティの属性から長さを取得できます。 – siride

+0

かなり大丈夫です。私はいくつかのことを工夫しています。目的は、40または50のルックアップを作成し、それぞれが異なる記述フィールド長を持つようにすることです。その最大長は検証のためのコード生成を促します。そうでなければ、私はすべての長さを250に設定し、それを使って完了します。 –

答えて

0

私はDescriptionプロパティが宣言された場合、あなたの例ではLookupクラスがあり、​​はあなたのプロパティが宣言されたタイプを与えることをかなり確信しています。 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()'メソッドについても全く知らなかった。十分にあなたに感謝することはできません! –