Skip to content

Instantly share code, notes, and snippets.

@lucasapoena
Last active February 21, 2022 12:05
Show Gist options
  • Save lucasapoena/dec29499faa890fdc7591aa5703591a9 to your computer and use it in GitHub Desktop.
Save lucasapoena/dec29499faa890fdc7591aa5703591a9 to your computer and use it in GitHub Desktop.
Relacionamento Many-to-Many no Entity Framework 3.1 (EF Core 3.1)
namespace Example.Dotnet
{
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
#region --- DBSets ---
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<ProductCategory> ProductCategories { get; set; }
#endregion
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductCategory>()
.HasKey(productCategory => new { productCategory.ProductId, productCategory.CategoryId });
modelBuilder.Entity<ProductCategory>()
.HasOne(productCategory => productCategory.Product)
.WithMany(product => product.ProductCategories)
.HasForeignKey(productCategory => productCategory.ProductId);
modelBuilder.Entity<ProductCategory>()
.HasOne(productCategory => productCategory.Category)
.WithMany(category => category.ProductCategories)
.HasForeignKey(productCategory => productCategory.CategoryId);
base.OnModelCreating(modelBuilder);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment