我有一個基類查找,如下:
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>
我知道這很煩人質疑的理由......但是,爲什麼你需要指定的類級屬性的長度?爲什麼不把你的任意長度放在代碼和描述字段上,並且在類上有一個IsLookup屬性,這個屬性不會花費太多時間?您始終可以使用反射來從屬性上的屬性中獲取長度。 – siride
很好 - 我做了一些工作。目的是構建40或50個查找,每個查找具有不同的描述字段長度。最大長度驅動代碼生成進行驗證,否則我只需將長度設置爲250即可完成驗證。 –