求通过Erwin API为Erwin模型添加关系的示例代码(含key_group)
使用Erwin API添加关系与Key Group示例代码
添加实体关系
Erwin模型中的关系通过Model.CreateRelationship方法创建,需指定关联的父、子实体,并可设置基数、名称等属性。以下是VBA和C#的示例:
VBA示例
' 连接到已运行的Erwin实例并获取当前模型 Dim erApp As Object Dim erModel As Object Set erApp = GetObject(, "Erwin.Modeler.Application") Set erModel = erApp.ActiveModel ' 按名称获取父、子实体(替换为你的实体名称) Dim parentEntity As Object Dim childEntity As Object Set parentEntity = erModel.Entities.Item("Customer") Set childEntity = erModel.Entities.Item("Order") ' 创建关系 Dim newRelationship As Object Set newRelationship = erModel.CreateRelationship(parentEntity, childEntity) ' 配置关系属性 newRelationship.Name = "Customer_Orders" newRelationship.ParentCardinality = "1" ' 父端基数:1 newRelationship.ChildCardinality = "N" ' 子端基数:N newRelationship.Description = "一个客户可关联多个订单" ' 保存模型变更 erModel.Save
C#示例(需引用Erwin Modeler COM组件)
using Erwin.Modeler; using System.Runtime.InteropServices; // 连接到Erwin实例 Application erApp = (Application)Marshal.GetActiveObject("Erwin.Modeler.Application"); Model erModel = erApp.ActiveModel; // 获取关联实体 Entity parentEntity = erModel.Entities["Customer"]; Entity childEntity = erModel.Entities["Order"]; // 创建并配置关系 Relationship newRelationship = erModel.CreateRelationship(parentEntity, childEntity); newRelationship.Name = "Customer_Orders"; newRelationship.ParentCardinality = "1"; newRelationship.ChildCardinality = "N"; newRelationship.Description = "一个客户可关联多个订单"; // 保存模型 erModel.Save();
添加Key Group及其属性
Key Group属于实体的子对象,需通过实体的KeyGroups.Create方法创建,再将属性添加到Key Group中。以下是示例:
VBA示例
' 获取目标实体(替换为你的实体名称) Dim targetEntity As Object Set targetEntity = erModel.Entities.Item("Order") ' 创建主键Key Group(kPrimaryKey为Erwin内置常量,值为1) Dim newKeyGroup As Object Set newKeyGroup = targetEntity.KeyGroups.Create("Order_PK", 1) ' 获取要添加到Key Group的属性(替换为你的属性名称) Dim keyAttr As Object Set keyAttr = targetEntity.Attributes.Item("Order_ID") ' 将属性添加到Key Group newKeyGroup.Attributes.Add keyAttr ' 配置Key Group描述 newKeyGroup.Description = "订单主键,唯一标识每个订单" ' 保存模型 erModel.Save
C#示例
// 获取目标实体 Entity targetEntity = erModel.Entities["Order"]; // 创建主键Key Group KeyGroup newKeyGroup = targetEntity.KeyGroups.Create("Order_PK", KeyType.kPrimaryKey); // 获取并添加属性到Key Group Attribute keyAttr = targetEntity.Attributes["Order_ID"]; newKeyGroup.Attributes.Add(keyAttr); // 设置描述 newKeyGroup.Description = "订单主键,唯一标识每个订单"; // 保存模型 erModel.Save();
关键注意事项
- 确保操作的实体、属性已存在,否则会抛出异常;
- Key Group类型对应
KeyType枚举:kPrimaryKey(主键)、kForeignKey(外键)、kAlternateKey(候选键)等; - 可通过
KeyGroups.Item方法检查Key Group是否存在,再决定是否创建。
内容的提问来源于stack exchange,提问作者Margaret
相关产品推荐
相关产品推荐

