fluent api many to many ef core code example
Example 1: many to many ef core
protected override void OnModelCreating(ModelBuilder modelBuilder){ modelBuilder.Entity<BookCategory>() .HasKey(bc => new { bc.BookId, bc.CategoryId }); modelBuilder.Entity<BookCategory>() .HasOne(bc => bc.Book) .WithMany(b => b.BookCategories) .HasForeignKey(bc => bc.BookId); modelBuilder.Entity<BookCategory>() .HasOne(bc => bc.Category) .WithMany(c => c.BookCategories) .HasForeignKey(bc => bc.CategoryId);}
Example 2: one to many relationship ef core
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Company Company { get; set; }
}