How To Insert Data In Many-To-Many Relationship Entity Framework Core?

How to Insert Data in a Many-to-Many Relationship with Entity Framework Core

Many-to-many relationships are a common occurrence in relational databases. They occur when a row in one table can be related to multiple rows in another table, and vice versa. For example, a customer can have multiple orders, and an order can have multiple items.

Entity Framework Core is a popular ORM (object-relational mapper) that can help you to easily work with data in a relational database. It provides a number of features that make it easy to insert data into many-to-many relationships, including:

  • The `ManyToMany` relationship type
  • The `Add` and `Remove` methods on the `ManyToMany` relationship
  • The `ToList()` method on the `ManyToMany` relationship

In this article, we will show you how to use these features to insert data into a many-to-many relationship with Entity Framework Core. We will use a simple example of a customer and order database to illustrate the concepts.

Getting Started

To follow along with this tutorial, you will need the following:

  • Visual Studio 2019 or later
  • The Entity Framework Core NuGet package
  • A SQL Server database

We will be using a simple database with two tables: `Customer` and `Order`. The `Customer` table has the following columns:

  • `Id` (int, primary key)
  • `Name` (nvarchar(max))

The `Order` table has the following columns:

  • `Id` (int, primary key)
  • `CustomerId` (int, foreign key to `Customer.Id`)
  • `OrderDate` (datetime)
  • `Total` (decimal)

We will create these tables in the next section.

Creating the Database

To create the database, open SQL Server Management Studio and connect to your database server. Then, create a new database called `EFCoreManyToMany`.

Once the database is created, right-click on the `Tables` folder and select **New** > **Table**. This will create a new table called `Customer`.

In the **General** tab, enter the following columns for the `Customer` table:

* **Id** (int, primary key)
* **Name** (nvarchar(max))

Click **Add** to add the column to the table.

Now, right-click on the `Tables` folder again and select **New** > Table. This will create a new table called `Order`.

In the General tab, enter the following columns for the `Order` table:

  • Id (int, primary key)
  • CustomerId (int, foreign key to `Customer.Id`)
  • OrderDate (datetime)
  • Total (decimal)

Click Add to add the column to the table.

Now that the tables are created, we can start inserting data into them.

Inserting Data into the Tables

To insert data into the tables, we can use the `Insert` method on the `DbContext` class. The `Insert` method takes a `DbSet` object as its first argument. A `DbSet` object represents a collection of entities of a particular type. In our case, we will be using the `Customer` and `Order` `DbSet` objects.

To insert a new customer, we can use the following code:

c
var customer = new Customer {
Name = “John Doe”
};

context.Customers.Add(customer);

context.SaveChanges();

This code will insert a new customer record into the `Customer` table.

To insert a new order, we can use the following code:

c
var order = new Order {
CustomerId = customer.Id,
OrderDate = DateTime.Now,
Total = 100.00
};

context.Orders.Add(order);

context.SaveChanges();

This code will insert a new order record into the `Order` table.

Creating the Many-to-Many Relationship

Now that we have inserted data into the tables, we can create the many-to-many relationship between them. To do this, we need to add a foreign key to the `Order` table that references the `CustomerId` column in the `Customer` table.

We can do this by using the following code:

c
modelBuilder.Entity().HasMany(o => o.Customers).With

| Column 1 | Column 2 | Column 3 |
|—|—|—|
| Step 1: Create the database tables. |
| Table 1: Products |
| Column 1: ProductID (int, primary key) |
| Column 2: Name (nvarchar(max)) |
| Table 2: Categories |
| Column 1: CategoryID (int, primary key) |
| Column 2: Name (nvarchar(max)) |
| Table 3: ProductCategories |
| Column 1: ProductID (int, foreign key, references Products) |
| Column 2: CategoryID (int, foreign key, references Categories) |

| Step 2: Create the Entity Framework Core model. |
csharp
public class Product {
public int ProductID { get; set; }
public string Name { get; set; }
}

public class Category {
public int CategoryID { get; set; }
public string Name { get; set; }
}

public class ProductCategory {
public int ProductID { get; set; }
public int CategoryID { get; set; }
}

| Step 3: Add the Many-To-Many relationship to the model. |
csharp
public class Product : IEntity {
public int ProductID { get; set; }
public string Name { get; set; }

public virtual ICollection ProductCategories { get; set; }
}

public class Category : IEntity {
public int CategoryID { get; set; }
public string Name { get; set; }

public virtual ICollection ProductCategories { get; set; }
}

public class ProductCategory : IEntity {
public int ProductID { get; set; }
public int CategoryID { get; set; }

public virtual Product Product { get; set; }
public virtual Category Category { get; set; }
}

| Step 4: Add the database context. |
csharp
public class ApplicationDbContext : DbContext {
public ApplicationDbContext(DbContextOptions options)
: base(options) { }

public DbSet Products { get; set; }
public DbSet Categories { get; set; }
public DbSet ProductCategories { get; set; }
}

| Step 5: Seed the database with some data. |
csharp
public class SeedData {
public static void Seed(ApplicationDbContext context) {
// Create some products.
var product1 = new Product {
ProductID = 1,
Name = “Product 1”
};
var product2 = new Product {
ProductID = 2,
Name = “Product 2”
};
var product3 = new Product {
ProductID = 3,
Name = “Product 3”
};
context.Products.AddRange(new[] { product1, product2, product3 });

// Create some categories.
var category1 = new Category {
CategoryID = 1,
Name = “Category 1”
};
var category2 = new Category {
CategoryID = 2,
Name = “Category 2”
};
var category3 = new Category {
CategoryID = 3,
Name = “Category 3”
};
context.Categories.AddRange(new[] { category1, category2, category3 });

// Create some product categories.
var productCategory1 = new ProductCategory {
ProductID = product1.ProductID,
CategoryID = category1.CategoryID
};
var productCategory2 = new ProductCategory {
ProductID = product2.ProductID,
CategoryID = category2.CategoryID
};
var productCategory3 = new ProductCategory {
ProductID = product3.ProductID,
CategoryID = category3.CategoryID
};
context.ProductCategories.AddRange(new[] { productCategory1, productCategory2, productCategory3 });

In this tutorial, you will learn how to insert data into a Many-to-Many relationship in Entity Framework Core. We will use the following example:

  • A `Student` entity has a `Many-to-Many` relationship with a `Course` entity.
  • A `Student` can take multiple `Courses`.
  • A `Course` can be taken by multiple `Students`.

We will create the database and the entities using Entity Framework Core, and then we will insert data into the database.

What is a Many-to-Many Relationship?

A Many-to-Many relationship is a relationship between two entities where one entity can have multiple instances of the other entity, and vice versa. For example, a student can have multiple courses, and a course can have multiple students.

In Entity Framework Core, a Many-to-Many relationship is represented by a join table. The join table contains the foreign keys for the two entities involved in the relationship.

In our example, the join table will have two columns:

  • `StudentId` – The foreign key for the `Student` entity.
  • `CourseId` – The foreign key for the `Course` entity.

How to Create a Many-to-Many Relationship in Entity Framework Core?

To create a Many-to-Many relationship in Entity Framework Core, you can use the following steps:

1. Create the database and the entities.
2. Add the Many-to-Many relationship to the entities.
3. Create the join table.
4. Add the foreign keys to the join table.
5. Add the navigation properties to the entities.

Create the Database and the Entities

First, we need to create the database and the entities. We can do this using the following commands:

dotnet ef database create

This will create a database called `Northwind`.

Next, we need to create the entities. We can do this using the following commands:

dotnet ef model add Student
dotnet ef model add Course

This will create two entities: `Student` and `Course`.

Add the Many-to-Many Relationship to the Entities

Next, we need to add the Many-to-Many relationship to the entities. We can do this by adding the following code to the `Student` entity:

public virtual ICollection Courses { get; set; }

This code creates a property called `Courses` on the `Student` entity. This property is a collection of `Course` entities.

We also need to add the Many-to-Many relationship to the `Course` entity. We can do this by adding the following code to the `Course` entity:

public virtual ICollection Students { get; set; }

This code creates a property called `Students` on the `Course` entity. This property is a collection of `Student` entities.

Create the Join Table

Next, we need to create the join table. We can do this by adding the following code to the `Student` entity:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasMany(s => s.Courses)
.WithMany(c => c.Students)
.OnDelete(DeleteBehavior.Cascade);
}

This code creates a join table called `StudentCourse`. The join table has two columns:

  • `StudentId` – The foreign key for the `Student` entity.
  • `CourseId` – The foreign key for the `Course` entity.

The `OnDelete(DeleteBehavior.Cascade)` code tells Entity Framework Core to delete the rows in the join table when a `Student` or `Course` entity is deleted.

Add the Foreign Keys to the Join Table

Next, we need to add the foreign keys to the join table. We can do this by adding the following code to the `StudentCourse` entity:

[Key]
public int StudentId { get; set; }

[Key]
public int CourseId { get; set; }

This code creates two columns in the join table:

  • `StudentId` – The foreign key for the `Student` entity.
  • `CourseId` – The foreign key for the `Course` entity.

The `[Key]` attribute tells Entity Framework Core that these columns are primary keys.

Add the Navigation Properties to the Entities

Finally, we need to add the navigation

3. Add a foreign key to the “many” side of the relationship

In a many-to-many relationship, the “many” side of the relationship is the side that has multiple rows in the database table. In the example above, the “many” side of the relationship is the `Orders` table.

To add a foreign key to the “many” side of the relationship, you need to add a column to the `Orders` table that references the primary key of the `Products` table. In this case, the primary key of the `Products` table is the `ProductId` column.

To add the foreign key, open the `Orders` table in the Entity Framework Core designer. In the `Properties` pane, click the `Add` button and select `Foreign Key`.

In the `Foreign Key` dialog box, select the `Products` table as the referenced table. In the `Column` field, select the `ProductId` column.

Click the `OK` button to add the foreign key.

4. Add a join table to the relationship

A join table is a table that is used to link two other tables together. In a many-to-many relationship, the join table contains the foreign keys from both the “many” side of the relationship and the “one” side of the relationship.

To add a join table to the relationship, right-click the `Orders` table in the Entity Framework Core designer and select `Add` > `Table`.

In the `Table` dialog box, type a name for the join table. In this case, we will name the join table `OrderDetails`.

Click the `Add` button to add the join table.

The join table will be added to the Entity Framework Core designer. The join table will have two columns:

  • `OrderId` – This column will store the foreign key from the `Orders` table.
  • `ProductId` – This column will store the foreign key from the `Products` table.

In this tutorial, you learned how to insert data into a many-to-many relationship in Entity Framework Core. You learned how to add a foreign key to the “many” side of the relationship and how to add a join table to the relationship.

By following these steps, you can easily create and maintain many-to-many relationships in your Entity Framework Core applications.

Q: How do I insert data into a many-to-many relationship in Entity Framework Core?

A: To insert data into a many-to-many relationship in Entity Framework Core, you can use the following steps:

1. Create a new entity type for the relationship.
2. Add a foreign key column to each entity type in the relationship.
3. Define the relationship between the entity types in the model.
4. Add data to the entity types.
5. Save the changes to the database.

Here is an example of how to insert data into a many-to-many relationship in Entity Framework Core:

c
// Create a new entity type for the relationship.
public class BookCategory {
public int BookId { get; set; }
public int CategoryId { get; set; }
}

// Add a foreign key column to each entity type in the relationship.
public class Book {
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection BookCategories { get; set; }
}

public class Category {
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection BookCategories { get; set; }
}

// Define the relationship between the entity types in the model.
public class BookCategoryModel : ModelBuilder {
public BookCategoryModel(DbContext context) : base(context) {
this.HasMany(b => b.BookCategories).WithMany(bc => bc.Book).HasForeignKey(bc => bc.BookId);
this.HasMany(c => c.BookCategories).WithMany(bc => bc.Category).HasForeignKey(bc => bc.CategoryId);
}
}

// Add data to the entity types.
Book book = new Book { Title = “The Lord of the Rings” };
Category category = new Category { Name = “Fantasy” };
BookCategory bookCategory = new BookCategory { BookId = book.Id, CategoryId = category.Id };

// Save the changes to the database.
context.SaveChanges();

Q: What are the different ways to insert data into a many-to-many relationship in Entity Framework Core?

A: There are two different ways to insert data into a many-to-many relationship in Entity Framework Core:

* **Using the fluent API:** You can use the fluent API to insert data into a many-to-many relationship by calling the `Add()` method on the relationship entity type. For example, the following code inserts a new book category into the database:

c
BookCategory bookCategory = new BookCategory { BookId = book.Id, CategoryId = category.Id };
context.BookCategories.Add(bookCategory);
context.SaveChanges();

* **Using the entity framework core CLI:** You can also use the entity framework core CLI to insert data into a many-to-many relationship. To do this, you can use the `insert` command. For example, the following command inserts a new book category into the database:

> ef core insert BookCategory –book-id 1 –category-id 2

Q: What are the limitations of using the fluent API to insert data into a many-to-many relationship in Entity Framework Core?

A: There are a few limitations to using the fluent API to insert data into a many-to-many relationship in Entity Framework Core:

  • You cannot insert data into a many-to-many relationship that has a composite foreign key.
  • You cannot insert data into a many-to-many relationship that has a self-referential foreign key.
  • You cannot insert data into a many-to-many relationship that has a circular foreign key.

Q: What are the limitations of using the entity framework core CLI to insert data into a many-to-many relationship in Entity Framework Core?

A: There are a few limitations to using the entity framework core CLI to insert data into a many-to-many relationship in Entity Framework Core:

  • You cannot insert data into a many-to-many relationship that has a composite foreign key.
  • You cannot insert data into a many-to-many relationship that has a self-referential foreign key.
  • You cannot insert data into a many-to-many relationship that has a circular foreign key.

In this blog post, we have discussed how to insert data in a many-to-many relationship using Entity Framework Core. We first created a model for the many-to-many relationship, then we created a migration to create the database tables. Finally, we used the Entity Framework Core API to insert data into the tables.

We hope that this blog post has been helpful. Please feel free to leave any questions or comments below.

Author Profile

Against Austerity
Against Austerity
Previously, our website was dedicated to the work of United Front Against Austerity (UFAA). Focused on addressing the economic challenges in the United States, UFAA was committed to fighting against austerity measures that threatened essential social programs. The group emphasized the need for substantial financial reforms to alleviate the economic depression, highlighting two key demands: Implementing a 1% Wall Street Sales Tax and Nationalization of the Federal Reserve System.

In 2023, our website underwent a significant transformation, pivoting from its previous focus on economic and political advocacy to becoming a resource for empowering people through information. Recognizing the evolving needs of our audience, we shifted towards providing in-depth, informative articles that address pressing questions and queries from various fields.

Our website’s transformation is a reflection of our commitment to providing valuable, in-depth information that empowers our readers. By adapting to changing times and needs, we strive to be a trusted source of knowledge and insight in an increasingly complex world.