使用Fluent API在POCO对象的BaseClass上设置MaxLength

时间:2012-09-07 11:18:13

标签: .net c#-4.0 entity-framework-4

我有一个基类,就像我的POCO对象一样

 public abstract class BASE
    {
        protected BASE()
        {
            Created = DateTime.UtcNow;
            Modified = Created;

        }

        public int id { get; set; }
        public DateTime Created { get; set; }
        public DateTime Modified { get; set; }
        [MaxLength(50)]
        public string CreatedBy { get; set; }
        [MaxLength(50)]
        public string ModifiedBy { get; set; }
    }

我想要做的是使用流畅的API设置“MaxLength(50)”属性。

但如果我在Context.ModelCreating

中这样做
modelBuilder.Entity<BASE>().Property(p => p.CreatedBy).HasMaxLength(50);
modelBuilder.Entity<BASE>().Property(p => p.ModifiedBy).HasMaxLength(50);

然后在数据库中生成“BASE”表 - 我想避免这种情况。

我缺少什么,能够在Fluent API中设置这些约束?

2 个答案:

答案 0 :(得分:1)

您可以使用EntityTypeConfiguration<TEntity>配置最大长度。

创建一个基类来映射BASE属性。

public class MyEntityMap<TEntity> : EntityTypeConfiguration<TEntity>
    where TEntity : BASE
{
    public MyEntityMap()
    {
        Property(p => p.CreatedBy).HasMaxLength(50);
        Property(p => p.CreatedBy).HasMaxLength(50);
    }
}

然后为每个派生类创建MyEntityMap<TEntity>

public class DerivedMap : MyEntityMap<Derived>
{
    public DerivedMap()
    {
        //mappings
    }
}

modelBuilder.Configurations.Add(new DerivedMap());

答案 1 :(得分:1)

我刚刚在Code First方法中使用了EF 6的答案。用于设置表的SQL脚本是按照我预期的方式生成的。所有列都映射到基类中,其中包含从此类派生的表脚本

public abstract class BaseMap<T> : EntityTypeConfiguration<T> where T : DbBase
    {
        protected BaseMap()
        {
            Ignore(t => t.DbGuid);

            // Properties

            Property(t => t.CreatedBy)
                .IsRequired()
                .HasMaxLength(50);

            Property(t => t.ChangedBy)
                .HasMaxLength(50);

            Property(t => t.DeletedBy)
                .HasMaxLength(50);

            Property(t => t.RowVersion)
                .IsRequired()
                .IsFixedLength()
                .HasMaxLength(8)
                .IsRowVersion()
                .IsConcurrencyToken();

            // Table & Column Mappings
            Property(t => t.CreatedAt).HasColumnName("CreatedAt");
            Property(t => t.CreatedBy).HasColumnName("CreatedBy");
            Property(t => t.ChangedAt).HasColumnName("ChangedAt");
            Property(t => t.ChangedBy).HasColumnName("ChangedBy");
            Property(t => t.DeletedAt).HasColumnName("DeletedAt");
            Property(t => t.DeletedBy).HasColumnName("DeletedBy");
            Property(t => t.RowVersion).HasColumnName("RowVersion");
        }
    }