How to: Create Links in Code

You can create links between model elements by using code. This action has the same effect as a language user connecting two elements by dragging a link from the Toolbox to the design surface.

Before you perform the steps in this topic, you should understand how to obtain a reference to the store and how to use transactions. For more information, see How to: Create Elements in Code.

To adding a link between elements in a model

  1. In your code, create an instance of a store (using the New keyword) or use a reference to a model or element in the store to access its Store property.

  2. Within a transaction, write the code to create links between elements.

    Each link that you add must be an instance of a relationship that is defined in the metadata for the domain model.

  3. Commit the transaction to save changes to the store.

  4. Dispose of the store.

The following example creates an instance of the store, adds elements to it, and then adds links between one element and the other elements in several ways.

Note Note

The code is written with the assumption that the Book class has already been defined.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Modeling;

namespace ConsoleApplication1
  class Program
    static void Main(string[] args)
      Store store = new Store();

      using (Transaction txCreateElem =  
        store.TransactionManager.BeginTransaction("Create elements"))
        Library a = new Library(store);
        Book b1 = new Book(store);
        Book b2 = new Book(store);
        Book b3 = new Book(store);
        Book b4 = new Book(store);

        // Create link by adding b1 to generated Books property of a

        // Create link by setting generated Library property of b2 to a
        b2.Library = a;

        // Create link by adding b1 to generated Books property of a

        // Create link between a and b4 with a LibraryHasBooks
        // constructor 
        new LibraryHasBooks(a, b4);

        // The constructor creates the link and sets the source and
        // target role players to the elements passed in as parameters.

        // You do not need a variable to hold the new instance of
        // LibraryHasBooks that the constructor returns
        // unless you want to use the variable later.

        // Commit the transaction and add the elements to the model