Foreign key

A foreign key in a table is the column that is set aside to reference a primary key in a different table. Just like a primary key, a foreign key may also be a combination of multiple columns.

When you have two different tables or entities that are related to each other, there are several ways they can be related. For example, you can have one-to-one , one-to-many , and many-to-many relationships.

We mainly used a [ForeignKey] attribute in the examples in this chapter in order to decorate a field that we wanted to use as a foreign key, but we can also use the Fluent API to define our foreign keys. We can use the .HasForeignKey() property for this:

protected override void OnModelCreating(ModelBuilder modelBuilder) 
    {       
      modelBuilder.Entity(typeof(GameSessionModel)) 
      .HasOne(typeof(UserModel), "User2") 
      .WithMany() 
      .HasForeignKey("User2Id")
.OnDelete(DeleteBehavior.Restrict); }

The preceding code snippet has several other attributes that we can use to define relationships between tables, examples of which include .HasOne() and .WithMany(). We will explain these later in this chapter.

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

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