You are on page 1of 2

How to: Implement Many-to-Many

Relationships
eXpress Persistent Objects > Examples > How to: Implement Many-to-Many Relationships

There are three types of relationships between objects. The type of a relationship that is
created depends upon how related objects are defined. To learn about a particular
relationship type, click a corresponding link below.

One-to-Many Relationships
One-to-One Relationships
Many-to-Many Relationships

This article demonstrates how to create many-to-many relationships in databases created by


XPO. If you are using XPO to map to existing databases, refer to the approach described in
the Mapping to an Existing Database online article.

XPO can handle Many-to-Many relationship between objects. In the following code example,
the Location class might contain several Departments and every Department can in turn
span several Locations.

C#VB
// Represents the Location class that contains its name and
information
// about the departments at the location.
public class Location: XPObject {
public Location(Session session) : base(session) { }
public string Name;
// Apply the Association attribute to mark the Departments
property
// as the many end of the LocationsDepartments association.
[Association("LocationsDepartments", typeof(Department))]
public XPCollection Departments { get { return
GetCollection("Departments"); }}
}

// Represents the Department class that contains its name


// and references all the locations of the department's offices.
public class Department: XPObject {
public Department(Session session) : base(session) { }
public string Name;
// Apply the Association attribute to mark the Locations
property
// as the many end of the LocationsDepartments association.
[Association("LocationsDepartments", typeof(Location))]
public XPCollection Locations { get { return
GetCollection("Locations"); }}
}

To create data use the following code.

C#
using DevExpress.Xpo;

// ...
public partial class Form1 : Form {
UnitOfWork uw;
public Form1() {
InitializeComponent();
uw = new UnitOfWork();
CreateData(uw);
}
private void CreateData(UnitOfWork uw) {
Department dep = new Department(uw);
dep.Name = "Department A";
Location loc = new Location(uw);
loc.Name = "USA";
dep.Locations.Add(loc);
loc = new Location(uw);
loc.Name = "UK";
dep.Locations.Add(loc);
uw.CommitChanges();
}
}

The code listed above is sufficient for XPO to work properly: it will generate all necessary
intermediate tables and relationships.

To use the association's name as the name of a junction table, set the
AssociationAttribute.UseAssociationNameAsIntermediateTableName property to true.

You might also like