Home > Backend Development > C++ > How to Define the Principal End in Entity Framework's 1:1 Relationships?

How to Define the Principal End in Entity Framework's 1:1 Relationships?

Susan Sarandon
Release: 2025-01-21 22:36:11
Original
901 people have browsed it

How to Define the Principal End in Entity Framework's 1:1 Relationships?

Master-side definition in Entity Framework 1:1 relationship

What is the main terminal?

In a 1:1 relationship, one entity must be designated as the master and the other entity as the slave. The master is the entity that owns the relationship or is responsible for maintaining the relationship, while the slave depends on the existence of the master entity.

Code error analysis

The error you are encountering in Entity Framework is caused by the main side not clearly defining the relationship between Foo and Boo. Entity Framework requires this specification to determine which entity's primary key will be used as the foreign key for the subordinate entity.

Master and slave in 1:1 relationship

In your code, the relationship between Foo and Boo is a one-to-one relationship. Here’s how to identify the master:

  • Main end: A end that can exist independently, that is, the entity responsible for creating or maintaining relationships.
  • Slave end: A end that depends on the master end, that is, an entity that can only exist when the master end exists.

In your example, Foo should be the master since it can exist independently of the Boo entity. Boo, on the other hand, depends on Foo because it needs to insert the Foo primary key into the database.

Configure the main terminal

There are two ways to configure the master side of a 1:1 relationship in Entity Framework:

Fluent Mapping:

<code class="language-csharp">modelBuilder.Entity<Foo>()
    .HasOptional(f => f.Boo)
    .WithRequired(s => s.Foo);</code>
Copy after login

Data annotation:

<code class="language-csharp">public class Foo
{
    [Key]
    public string FooId { get; set; }
    public Boo Boo { get; set; }
}

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId { get; set; }
    public Foo Foo { get; set; }
}</code>
Copy after login

By defining the master, you specify that Foo owns the relationship, and Boo can only exist if the corresponding Foo record exists.

The above is the detailed content of How to Define the Principal End in Entity Framework's 1:1 Relationships?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template