Sobes.tech
Junior — Middle

How can a one-to-one relationship between two entities be implemented?

sobes.tech AI

Answer from AI

A one-to-one relationship between two entities in C# is usually implemented through navigation properties and keys. For example, if there are classes Person and Passport, where each person has one passport, you can do it like this:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Passport Passport { get; set; }
}

public class Passport
{
    public int Id { get; set; }
    public string Number { get; set; }

    public int PersonId { get; set; }  // foreign key
    public Person Person { get; set; }
}

In the database, the PersonId field in the Passport table will be unique and reference Person. In Entity Framework, you can further configure this relationship using Fluent API to specify that it is indeed one-to-one.

Thus, each entity contains a reference to the other, and the relationship is maintained through a foreign key with a uniqueness constraint.

How can a one-to-one relationship between two… - sobes.tech