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:
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>
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>
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!