Skip to main content
A newer version of this page is available. .
.NET Framework 4.5.2+

How to: Implement One-to-One Relationships

  • 3 minutes to read

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.

 

Let’s consider a simple example of a One-to-One relationship, when both classes that participate in the relationship have properties with a reference to the instance of their opposite class. It’s necessary to write extra code within the property’s setter method for each class that participates in the relationship to ensure the relationship’s integrity, i.e. when a new object is assigned to a reference property, the reference to the previous object instance should be cleared and the assigned object should reference the current one.

This technique can be implemented as shown in the following code example.

// Represents the Building class which refers to the building's owner.
public class Building : XPObject {
    Person owner = null;
    public Person Owner {
        get { return owner; }
        set {
            if(owner == value)
                return;

            // Store a reference to the former owner.
            Person prevOwner = owner;
            owner = value;

            if(IsLoading) return;

            // Remove an owner's reference to this building, if exists.
            if(prevOwner != null && prevOwner.House == this)
                prevOwner.House = null;

            // Specify that the building is a new owner's house.
            if(owner != null)
                owner.House = this;
            OnChanged(nameof(Owner));
        }
    }
}

// Represents the Person class which refers to the person's house.
public class Person : XPObject {
    Building house = null;
    public Building House {
        get { return house; }
        set {
            if(house == value)
                return;

            // Store a reference to the person's former house.
            Building prevHouse = house;
            house = value;

            if(IsLoading) return;

            // Remove a reference to the house's owner, if the person is its owner.
            if(prevHouse != null && prevHouse.Owner == this)
                prevHouse.Owner = null;

            // Specify the person as a new owner of the house.
            if(house != null)
                house.Owner = this;

            OnChanged(nameof(House));
        }
    }
}
See Also