关系生成器


  RelationshipBuilder 类用于为实体定义关系,但是如果实体的结构遵循一定的规则(可参考 关系映射),则也不需要使用此构造器。

  DefineRelation 方法用于定义两个实体类的关联关系。如下所示:

[TestMethod]
public void TestBuildRelationship()
{
    var assemblyBuilder = new DynamicAssemblyBuilder("TestAssembly");
    
    //定义仓库类
    var warehouseBuilder = new EntityTypeBuilder("Warehouse", assemblyBuilder);
    warehouseBuilder.SetCustomAttribute(() => new EntityMappingAttribute("warehouse"));
    warehouseBuilder.Properties.Add(new GeneralProperty() 
    { 
        Name = "Id",
        Type = typeof(int), 
        Info = new PropertyMapInfo
        { 
            ColumnName = "Id", 
            IsPrimaryKey = true, 
            GenerateType = IdentityGenerateType.AutoIncrement
        } 
    });

    warehouseBuilder.Properties.Add(new GeneralProperty() 
    { 
        Name = "Name", 
        Type = typeof(string),
        Info = new PropertyMapInfo 
        {
            ColumnName = "Name"
        } 
    });
    
    warehouseBuilder.Properties.Add(new GeneralProperty() 
    { 
        Name = "ProductId", 
        Type = typeof(int), 
        Info = new PropertyMapInfo 
        { 
            ColumnName = "ProductId"
        } 
    });
    
    warehouseBuilder.Properties.Add(new EntityProperty() 
    {
        Name = "Product", 
        Type = typeof(Products) 
    });
    
    //定义产品类
    var productBuilder = new EntityTypeBuilder("Products", assemblyBuilder);
    productBuilder.SetCustomAttribute(() => new EntityMappingAttribute("product"));
    productBuilder.Properties.Add(new GeneralProperty() 
    { 
        Name = "Id",
        Type = typeof(int), 
        Info = new PropertyMapInfo
        { 
            ColumnName = "Id", 
            IsPrimaryKey = true, 
            GenerateType = IdentityGenerateType.AutoIncrement
        } 
    });

    productBuilder.Properties.Add(new GeneralProperty() 
    { 
        Name = "Name", 
        Type = typeof(string),
        Info = new PropertyMapInfo 
        {
            ColumnName = "Name"
        } 
    });
    
    //构造类型
    var warehouseType = warehouseBuilder.Create();
    var productType = productBuilder.Create();
    
    //定义关系
    var relationBuilder = new RelationshipBuilder(assemblyBuilder);
    relationBuilder.DefineRelation(warehouseType, productType, "ProductId=>Id");
}