'
I have 2 database tables:
- College
- Course
Now I want to create an additional table for CollegeCourses
but it should have also 2 foreign keys from College
and Course
table.
If I want one foreign key on a table then I can do like this:
modelBuilder.Entity<Course>().OwnsMany(f => f.CollegeCourses);
I'm not sure on what to do if I try to add two foreign keys in one table.
I tried this one but it didn't work, it creates another table instead of just CollegeCourses
:
modelBuilder.Entity<College>().OwnsMany(f => f.CollegeCourses);
modelBuilder.Entity<Course>().OwnsMany(f => f.CollegeCourses);
SOLVED: Thanks for the help guys!
I found this on the link provided by @Hassan:
Fluent API, many-to-many in Entity Framework Core
'
I'm a bit confused on why there are two foreign key as a primary key on a table. How do I get those data without an Id holding them?
And I created a sample based on the code above but the difference is that I added a variable Id as my primary key.
modelBuilder.Entity<CollegeCourse>().HasKey(pc => new { pc.Id });
modelBuilder.Entity<CollegeCourse>()
.HasOne(pc => pc.College)
.WithMany(p => p.CollegeCourses)
.HasForeignKey(pc => pc.CollegeId);
modelBuilder.Entity<CollegeCourse>()
.HasOne(pc => pc.Course)
.WithMany(c => c.CollegeCourses)
.HasForeignKey(pc => pc.CourseId);
The database sample table look like this: