Skip to main content

Get related model

To get related model by specifying field name, use GetFieldValues method of IModel object.

public void GetFieldValues(ICommandContext c, ICommandParams p) 
{
//Get the model being displayed
IModel model = c.App.Workspace.CurrentModel;

//Get the related model by specifying the field name
var fieldName = "SomeFieldName";
IModelCollection relatedModels = model.GetFieldValues(fieldName);

//Output the model name
c.App.Output.WriteLine("sample", $"Model: {model.Name}");

//Output the related model name
c.App.Output.WriteLine("sample", $"FieldName: {fieldName}");
foreach (IModel relatedModel in relatedModels)
{
c.App.Output.WriteLine("sample", $"Related Model: {relatedModel.Name} ");
}
}

Getting from an association

When you get an association, you can get the model at the other end of the association by checking the association ends (the Source property and Target property of the IRelationship object).

public void GetRelatedModelsFromRelationship(ICommandContext c, ICommandParams p) 
{
//Get the relationship by specifying the Id
IRelationship relationship = c.App.Workspace.CurrentProject.GetRelationshipById("SomeRelationshipId");

//Get the related ends (source and destination) from the relationship
IModel source = relationship.Source;
IModel target = relationship.Target;

c.App.Output.WriteLine("sample", $"Relationship: {relationship.Name} ");
c.App.Output.WriteLine("sample", $" Source: {source.Name} ");
c.App.Output.WriteLine("sample", $" Target: {target.Name} ");
}