How do I create a ModelElement via API
My eighteenth How do I is up.
Scenario
Let's say that we start from the Minimal Language DSL template and we have an ExampleElement domain class that has a Name domain property with the Is Element Name flag set to true.
Because it has the IsElementName flag, every time that we create a ExampleElement with the UI (toolbox or model explorer) the element is created with a default name. This default name is composed of the type name of the concept plus an index. Example : ElementName1, ElementName2, etc.
The focus of this How do I shows how to create the model element programmatically.
Interfaces and classes needed
Code snippet
Wrong way:
private void CreateElement(Store store)
{
using(Transaction tx = store.TransactionManager.BeginTransaction("Add ExampleElement"))
{
ExampleModel root = store.ElementDirectory.FindElements<ExampleModel>().First() as ExampleModel;
ExampleElement element =
this.Store.ElementFactory.CreateElement(ExampleElement.DomainClassId) as ExampleElement;
root.Elements.Add(element);
tx.Commit();
}
}
Right way:
private void CreateElement(Store store)
{
using(Transaction tx = store.TransactionManager.BeginTransaction("Add ExampleElement"))
{
ExampleModel root = store.ElementDirectory.FindElements<ExampleModel>().First() as ExampleModel;
ExampleElement element =
store.ElementFactory.CreateElement(ExampleElement.DomainClassId) as ExampleElement;
ElementOperations elementOperations =
new ElementOperations(store as IServiceProvider, store);
ElementGroup elementGroup = new ElementGroup(store);
elementGroup.Add(element);
elementGroup.MarkAsRoot(element);
elementOperations.MergeElementGroup(root, elementGroup);
tx.Commit();
}
}
Assemblies needed
- Microsoft.VisualStudio.Shell.Interop
- Microsoft.VisualStudio.Modeling.Sdk.Shell
- Microsoft.VisualStudio.Modeling.Sdk.Diagrams
Stay tuned,
Pablo