Last active
February 21, 2022 12:05
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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