EF7使用Fluent根据类型和名称设置默认属性配置

时间:2018-11-29 01:21:40

标签: c# entity-framework

在EF6中,我可以通过使用OnModel创建以下内容来定义我的默认数据库属性

//Strings In General unless otherwise specified in metadata are Varchar(50) Not Null
modelBuilder.Properties<string>().Where(p => p.Name != "CreatedByUsername" || p.Name != "LastEditByUsername" || p.Name != "DeletedByUsername").Configure(p => p.HasMaxLength(50).IsRequired());//Required and Length(50)
//Common Table Username Fields
modelBuilder.Properties<string>().Where(p => p.Name == "CreatedByUsername" || p.Name == "LastEditByUsername" || p.Name == "DeletedByUsername").Configure(p => p.IsOptional().HasMaxLength(128));
modelBuilder.Properties<string>().Where(p => p.Name.EndsWith("Email")).Configure(p => p.HasMaxLength(100));
modelBuilder.Properties<string>().Where(p => p.Name.EndsWith("Username")).Configure(p => p.HasMaxLength(128).IsRequired());
modelBuilder.Properties<string>().Where(p => p.Name.EndsWith("Description")).Configure(p => p.HasMaxLength(200).IsRequired());
modelBuilder.Properties<string>().Where(p => p.Name.EndsWith("Comment") || p.Name.EndsWith("Note")).Configure(p => p.HasMaxLength(250));
modelBuilder.Properties<string>().Where(p => p.Name.EndsWith("Note") || p.Name.EndsWith("Note")).Configure(p => p.HasMaxLength(250));
modelBuilder.Properties<string>().Where(p => p.Name.EndsWith("Code")).Configure(p => p.HasMaxLength(20).IsRequired());
//Date fields are date or datetime based on naming convention
modelBuilder.Properties<DateTime>().Where(p => p.Name.EndsWith("Date")).Configure(p => p.HasColumnType("DateTime2"));
modelBuilder.Properties<DateTime>().Where(p => p.Name.EndsWith("DateTime") || p.Name == "LastEditDateTime" || p.Name == "CreatedDateTime" || p.Name == "DeletedDateTime").Configure(p => p.HasColumnType("DateTime"));
//Optional Values for these date and times
modelBuilder.Properties<DateTime>().Where(p => p.Name == "LastEditDateTime" || p.Name == "DeletedDateTime").Configure(p => p.IsOptional());

但是在ef7中,要说符合这些命名规则的所有字符串值都应用配置并不是那么容易。

   protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfiguration(new ApplicationUserMap());

        var strProperties = modelBuilder
            .Model
            .GetEntityTypes()
            .SelectMany(e => e.GetProperties())
            .Where(p => p.ClrType == typeof(string))
            .ToList();
        foreach (var property in modelBuilder.Model.GetEntityTypes()
            .SelectMany(t => t.GetProperties())
            .Where(prop => prop.ClrType == typeof(string)))
        {
            if (property.Name.EndsWith("Email"))
            {
              property.AsProperty().Builder.HasMaxLength(100,ConfigurationSource.Convention);
            }
            //.... Other if statements here
        }

问题是:是否有比ef6方法更有效的方法,比迭代所有实体和属性然后更有效地应用

0 个答案:

没有答案