Skip to main content

Add a model

This explains how to add a child model to a model field.

Add a model to a field

To add a model to a specific field of a model, use the AddNewModel method of the IModel object. The addition destination is the end.

public void AddNewModel(ICommandContext c, ICommandParams p) 
{
IModel model = c.App.Workspace.CurrentModel;
//Add a model of the "SoftwareComponent" metaclass to the "Components" field
model.AddNewModel("Components", "SoftwareComponent");
}

Add a model to a specified position

To add a model to a specific field and specific position of a model, use the AddNewModelAt method or AddNewModelTo method of the IModel object. The addition destination is the end. The following is an example of adding a model before the model named "Function Requirements" in the child element model of "Lane Keep Assist Function Requirements".

public void AddNewModelTo(ICommandContext c, ICommandParams p) 
{
IModel model = c.App.Workspace.CurrentProject.GetAllChildren().FirstOrDefault(m => m.Name == "Lane Keep Assist Function Requirement");
var targetModel = model.GetAllChildren().FirstOrDefault(m => m.Name == "Functional Requirement");
string fieldName = "SubRequirements";
string className = "SystemFunctionalRequirement";

var addModel = model.AddNewModelTo(fieldName, className, "before", targetModel);
c.App.Output.WriteLine("sample", $"{addModel.Name} has been added to field: {fieldName} of model: {model.Name}.");
}