0

情况:

我有一个基类Lookup,如下:

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

...并用于OnModelCreatingMaxLength属性 Description 设置为 40。

我已经能够编写一些看起来应该可以工作的东西,并且add-migration运行得很好,但是生成的迁移没有设置 maxlength:

  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>

4

1 回答 1

0

我很确定这DeclaringType将为您提供声明属性的类型,在您的示例中,Lookup类是Description声明属性的位置。由于Lookup没有该IsLookup属性,因此没有设置任何内容。尝试先查看已注册的类型,然后在找到后设置 Description 列:

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);
    });
于 2016-06-16T19:05:27.090 回答