[Entity Framework] Code First – Convention for Relationships

Tables in database can be related. (That’s why relational database are named for.) Let’s find out how convention works for relationships and how to configure them using data annotations and Fluent API.

 

1. One-to-Many Relationships

One-to-Many relationship is the most common relationship between tables. Usually it is a link between the primary key in one table (One side) and the foreign key in another table (Many side). In the following example, Category can have multiple products. (One category and many products.)

public class Category
{
  public int Id { get; set; }
  public string Name { get; set; }
  public List<Product> Products { get; set; }
}

public class Product
{
  public int Id { get; set; }
  public string Name { get; set; }
  public Category Category { get; set; }
}

public class ProductContext : DbContext
{
  public DbSet<Category> Categories { get; set; }
  public DbSet<Product> Products { get; set; }
}

If one or more of the following conditions are met, the one-to-many relationship is created in database.

  • In the “One-side” class, provides the list of many-side objects
  • In the “Many-side” class, provides the property to the one-side objects

If Code First find the one-to-many relationship, it creates the foreign key column in the “many-side” table. The default name of the column is <Name_of_One_side_table>_<Primary_key_name>. In our example, the “Products” table will get the “Category_Id” column.

 

2. Convention for One-to-Many Relationships

Let’s summarize when Code First creates a one-to-many relationship (Class A – Class B) for you.

[Case 1]

  • When a class A contains a collection navigation property
  • AND
  • When a class B contains a reference to  a navigation property

[Case 2]

  • When a class A contains a collection navigation property

[Case 3]

  • When a class B contains a reference to  a navigation property

 

3. Convention for Many-to-Many Relationships

[Case 1]

  • When class A contains a collection navigation property
  • AND
  • When class B contains a collection navigation property

 

4. Convention for One-to-on Relationships

[Case 1]

  • When a class A contains a reference to  a navigation property
  • AND
  • When a class B contains a reference to  a navigation property

In one-to-one relationship, you need to provide which is primary and which is dependent.

 

5. Convention for Foreign Keys

By default, Code First assumes any relationship is optional and does not create a foreign key.


			

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s