Purchase Courses Endpoint
In this lesson, we're going to create the purchase courses endpoint
Purchase courses endpoint#
Now that we have our clearBasket endoint, let's start working on the purchase courses endpoint. This one is not as straightforward as the previous one. To add courses to user's account, we need to create a relationship between users and courses, and this relationship will be a many-to-many relationship because a user can have multiple courses and a course can have multiple users. Since we're using a code first approach, we will have to make some changes to our models.
First of all, we'll have to create a new table which will be called UserCourse since it will work as a connection between User table and the Course table. Let's create a new modal with name, UserCourse. Now this table will have UserId and a CourseId column. Let's start with UserId property which is a string. Since we're creating a connection, we will also pass User proprty with the same name. Let's now create courseId property which has a type Guid. We also need to create a property with name, Course. We can import Guid as well. Now that we have created the UserCourse modal, we need to add this to the other two models. Let's start with the user. Here, we need to add an ICollection of UserCourse and we can call it UserCourses. The same way, inside Course modal, we can copy this and paste because it should exactly be the same.
Now inside the StoreContext, we can create DbSet of type UserCourse and we will call this UserCourses. Doing this won't be sufficient. We will have to write the configuration too, so let's do it inside OnModalCreating method. This is going to be for entity UserCourse, so we can write builder dot Entity UserCourse. Since this table will have two keys, we can write .HasKey and inside, we will write uc which stands for user key. This will be new uc.UserId and uc.CourseId. Now let's write configuration for many-to-many relationship. Let's write builder.entity of type UserCourse, and since one user can have many courses, we will write .HasOne, uc goes to uc.User; .WithMany, u goes to u.userCourses; and the foreign key will be uc.userId, so we can write .HasForeignKey, uc goes to uc dot userId. We can copy to establish other side of the relationship. We will replace User with Course and foreign key will be CourseId instead of UserId.