Skip to main content

Find the owner of a model

This explains how to find parent models (ancestors) in the model ownership hierarchy.

Get the owner model

To find the direct owner model, use the Owner property of the IModel object.

public void GetOwner(ICommandContext c, ICommandParams p) 
{
IModel model = c.App.Workspace.CurrentModel;

//Owner model
IModel owner = model.Owner;

//...
}

Find all parents

To get all owner instances that can be searched by ownership, use the GetOwners method of the IModel object.

public void GetOwners(ICommandContext c, ICommandParams p) 
{
IModel model = c.App.Workspace.CurrentModel;

var owners = model.GetOwners();

c.App.Output.WriteLine("sample", $"Model: Get owner instances of {model.Name}.");

if (!owners.Any())
{
c.App.Output.WriteLine("sample", "No owner instances.");
}
else
{
int count = 1;
foreach (var owner in owners) {
c.App.Output.WriteLine("sample", $"{count} item name: {owner.Name}");
count++;
}
}
}

Get the parent of a specific metamodel

To search for the parent of a specific class among its parents, including its ancestors, use the FindOwnerByClass method of the IModel object. The FindOwnerByClass method gets the first owner instance of the specified class that holds the model instance.

public void FindOwnerByClass(ICommandContext c, ICommandParams p) 
{
IModel model = c.App.Workspace.CurrentModel;
string className = "SystemRequirementSpecificationLayer";

var owner = model.FindOwnerByClass(className);

c.App.Output.WriteLine("sample", "Get Owner Instance (FindOwnerByClass)");

if (owner != null)
{
c.App.Output.WriteLine("sample", $"Model: {model.Name} has {className} class owner instance {owner.Name}.");
}
else
{
c.App.Output.WriteLine("sample", $"Model: {model.Name} has no {className} class owner instance.");
}
}

Check the project to which the model belongs

To check the project to which the model belongs, you can use the OwnerProject property of the IModel object, but if you simply want to access the currently open project, you can also use the CurrentProject property of the IWorkspace object.

public void OwnerProject(ICommandContext c, ICommandParams p) 
{
IModel model = c.App.Workspace.CurrentModel;
var project = model.OwnerProject;

//You can also simply use this
//var project = c.App.Workspace.CurrentProject;

c.App.Output.WriteLine("sample", project.Name);
}