One-to-one relationships

When we have a one-to-one relationship, we can say that a record in one table will only be able to have a relationship with exactly one record in another table. 

For example, if we have a User class and a UserAvatar class, and a user has one and only one avatar, then we can represent this using the Fluent API, as follows:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOne(u => u.UserAvatar)
.WithOne(a => a.User)
.HasForeignKey<UserAvatar>(u => u.UserForeignKey);
}

In the preceding code snippet, we have a one-to-one relationship between the user and their avatar. This is represented by the code in bold, that is, .HasOne(u => u.UserAvatar).WithOne(a => a.User). It applies both ways.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.197.163