实体生成器


  EntityTypeBuilder 类型可以通过指定一组 IProperty 来构造一个实体类型。实体类一般是继承自 EntityObject 类,当然你也可以在实例化构造器时指定实体所继承的基类。如下所示:

[TestMethod]
public void TestBuildEntityType()
{
    var builder = new EntityTypeBuilder("Warehouse");
    builder.Properties.Add(new GeneralProperty() 
    { 
        Name = "Id",
        Type = typeof(int), 
        Info = new PropertyMapInfo
        { 
            ColumnName = "Id", 
            IsPrimaryKey = true, 
            GenerateType = IdentityGenerateType.AutoIncrement
        } 
    });

    builder.Properties.Add(new GeneralProperty() 
    { 
        Name = "Name", 
        Type = typeof(string),
        Info = new PropertyMapInfo 
        {
            ColumnName = "Name"
        } 
    });
    
    builder.Properties.Add(new GeneralProperty() 
    { 
        Name = "Quantity", 
        Type = typeof(decimal), 
        Info = new PropertyMapInfo 
        { 
            ColumnName = "Quantity",
            Scale = 2 
        } 
    });
    
    builder.Properties.Add(new EntityProperty() 
    {
        Name = "Product", 
        Type = typeof(Products) 
    });
    
    //添加映射特性
    builder.SetCustomAttribute(() => new EntityMappingAttribute("warehouse"));
    
    var entityType = builder.Create();
}

  如果你需要同时构造很多实体类型,则可以使用统一的一个 DynamicAssembyBuilder 对象(可参考 Emit 构造器)。如下所示:

[TestMethod]
public void TestBuildWithAssembyBuilder()
{
    var assemblyBuilder = new DynamicAssemblyBuilder("TestAssembly");
    var builder1 = new EntityTypeBuilder("Warehouse", assemblyBuilder);
    var builder2 = new EntityTypeBuilder("Employee", assemblyBuilder);
    var builder3 = new EntityTypeBuilder("Storage", assemblyBuilder);
}

  使用 DefineValidateRule 方法为属性添加数据验证特性(可参考 数据验证映射)。如下所示:

[TestMethod]
public void TestBuildEntityType()
{
    var builder = new EntityTypeBuilder("Warehouse");
    var propId = new GeneralProperty() 
    { 
        Name = "Id",
        Type = typeof(int), 
        Info = new PropertyMapInfo 
        { 
            ColumnName = "Id", 
            IsPrimaryKey = true, 
            GenerateType = IdentityGenerateType.AutoIncrement
        } 
    };

    var propName = new GeneralProperty() 
    { 
        Name = "Name", 
        Type = typeof(string),
        Info = new PropertyMapInfo 
        {
            ColumnName = "Name"
        } 
    };
    
    var propQuantity = new GeneralProperty() 
    { 
        Name = "Quantity", 
        Type = typeof(decimal), 
        Info = new PropertyMapInfo 
        { 
            ColumnName = "Quantity",
            Scale = 2 
        } 
    };
    
    builder.DefineValidateRule(propName, () => new RequiredAttribute());
    builder.DefineValidateRule(propName, () => new MaxLengthAttribute(15));
    
    builder.Properties.Add(propId);
    builder.Properties.Add(propName);
    builder.Properties.Add(propQuantity);
    
    //添加映射特性
    builder.SetCustomAttribute(() => new EntityMappingAttribute("warehouse"));
    
    var entityType = builder.Create();
}