Zum Hauptinhalt springen
Echtzeit-Radar & Feeds
Alle RSS Feeds ➔
👥 Community & Social
Windows Tipps & SecurityGrafikkarte vor Überhitzung schützen: So geht’s(25.09.2026 um 08:00 Uhr)
••••••••••
Windows Tipps & SecurityGrafikkarte vor Überhitzung schützen: So geht’s(25.09.2026 um 08:00 Uhr)
••••••••••
Intelligence View
⚡ tsecurity.de Intelligence

EFCore Tutorial P4:Cleaning Up `OnModelCreating`

As your Entity Framework Core model grows, managing the configuration logic in the OnModelCreating method can become challenging. To keep the code clean, maintainable, and scalable, it’s important to modularize the entity configurations. I…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

As your Entity Framework Core model grows, managing the configuration logic in the OnModelCreating method can become challenging. To keep the code clean, maintainable, and scalable, it’s important to modularize the entity configurations. In this article, we’ll explore three approaches to clean up the configuration logic in OnModelCreating:




  1. Using IEntityTypeConfiguration for the Product entity

  2. Using Extension Methods for the Category entity

  3. Using Partial Classes for the ProductSupplier entity









1. Using IEntityTypeConfiguration for Product



IEntityTypeConfiguration is a great way to modularize the configuration logic for each entity into its own class. Let’s see how we can use this approach to configure the Product entity.






Step 1: Create the ProductConfiguration Class



Create a new class ProductConfiguration.cs to configure the Product entity separately:




using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
// Configure properties
builder.Property(p => p.Name)
.HasField("_name"); // Use backing field for Name

builder.Property(p => p.Price)
.HasColumnType("decimal(18,2)");



// One-to-One relationship with Inventory
builder.HasOne(p => p.Inventory)
.WithOne(i => i.Product)
.HasForeignKey<Inventory>(i => i.ProductId);


}
}









Step 2: Apply Configuration in AppDbContext



In AppDbContext, use ApplyConfiguration to apply the Product configuration:




public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Inventory> Inventories { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<ProductSupplier> ProductSuppliers { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Apply Product configuration using IEntityTypeConfiguration
modelBuilder.ApplyConfiguration(new ProductConfiguration());
}
}






This approach separates the Product configuration logic, making the AppDbContext cleaner and easier to maintain.









2. Using Extension Methods for Category



Using extension methods is another great way to modularize configuration logic for an entity. Let’s apply this approach to the Category entity.






Step 1: Create Extension Method



Create an extension method to configure the Category entity in a new file called ModelBuilderExtensions.cs:




public static class ModelBuilderExtensions
{
public static void ConfigureCategory(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>(entity =>
{
entity.HasKey(c => c.Id);
entity.Property(c => c.Name).IsRequired().HasMaxLength(50);

// One-to-Many relationship with Products
entity.HasMany(c => c.Products)
.WithOne(p => p.Category)
.HasForeignKey(p => p.CategoryId);
});
}
}









Step 2: Apply Extension Method in AppDbContext



In AppDbContext, use the extension method to apply the Category configuration:




public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Inventory> Inventories { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<ProductSupplier> ProductSuppliers { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Apply Product configuration using IEntityTypeConfiguration
modelBuilder.ApplyConfiguration(new ProductConfiguration());

// Apply Category configuration using extension method
modelBuilder.ConfigureCategory();
}
}






Using extension methods for the Category configuration makes it easier to extend and maintain your code.









3. Using Partial Classes for ProductSupplier



When you have complex relationships like Many-to-Many configurations, using partial classes allows you to distribute the configuration logic across multiple files, keeping the code modular and clean. Let’s apply this approach to configure the ProductSupplier entity.






Step 1: Create Partial Class for ProductSupplier Configuration



Create a new partial class in a separate file named AppDbContext.ProductSupplierConfiguration.cs to configure the ProductSupplier entity:




public partial class AppDbContext : DbContext
{
private void ConfigureProductSupplier(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductSupplier>()
.HasKey(ps => ps.Id); // Define primary key for ProductSupplier

modelBuilder.Entity<ProductSupplier>()
.HasOne(ps => ps.Product) // Configure the relationship to Product
.WithMany(p => p.ProductSuppliers)
.HasForeignKey(ps => ps.ProductId);

modelBuilder.Entity<ProductSupplier>()
.HasOne(ps => ps.Supplier) // Configure the relationship to Supplier
.WithMany(s => s.ProductSuppliers)
.HasForeignKey(ps => ps.SupplierId);

modelBuilder.Entity<ProductSupplier>()
.ToTable("ProductSuppliers"); // Define the table name
}
}









Step 2: Modify OnModelCreating to Call the Partial Class Method



Now, in the main AppDbContext class, call the ConfigureProductSupplier method in OnModelCreating:




public partial class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Inventory> Inventories { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<ProductSupplier> ProductSuppliers { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Apply Product configuration using IEntityTypeConfiguration
modelBuilder.ApplyConfiguration(new ProductConfiguration());

// Apply Category configuration using extension method
modelBuilder.ConfigureCategory();

// Apply ProductSupplier configuration using partial class method
ConfigureProductSupplier(modelBuilder);
}
}






By splitting the configuration logic for ProductSupplier into a partial class, the code is easier to manage, especially as the number of entities and relationships grows.









Conclusion



By applying these techniques, we achieve a more modular, maintainable, and scalable codebase in Entity Framework Core:





  1. Using IEntityTypeConfiguration for the Product entity ensures that each entity has its configuration class, which improves modularity.


  2. Using Extension Methods for the Category entity provides a flexible way to apply configurations that can be reused across different contexts.


  3. Using Partial Classes for the ProductSupplier entity allows you to split large and complex configurations into smaller, more manageable pieces, keeping the DbContext class clean.



These strategies will help you maintain a cleaner OnModelCreating method and improve the maintainability of your codebase.

Source Code EFCoreDemo

1. Sofort-Triage & Abwehrmaßnahmen

SOC Incident Playbook: Remote Code Execution (RCE) Defense
Syntax validiert (0 Fehler)
title: Detect Exploitation - EFCore Tutorial P4:Cleaning Up `OnModelCreating`
id: d239be90-0e8a-4a3f-980e-e997afb42384
status: experimental
description: Automatisch generierte SIEM-Erkennungsregel basierend auf CTI Intelligence
references:
  - https://tsecurity.de/
author: iShareStuff CTI Automated Detection Engine
date: 2026-09-25
logsource:
  category: network_connection
  product: any
detection:
  selection:
      CommandLine|contains:
        - 'exploit'
  condition: selection
falsepositives:
  - Legitime administrative Zugriffe oder Penetrationstests
level: high
tags:
  - attack.initial_access
Syntax validiert (0 Fehler)
rule CTI_Threat_Indicator {
    meta:
        author = "iShareStuff CTI Automated Detection Engine"
        date = "2026-09-25"
        description = "YARA Signature for "
    strings:
        $str = "EFCore Tutorial P4:Cleaning Up" ascii wide
    condition:
        any of them
}
Syntax validiert (0 Fehler)
index=security sourcetype IN ("cisco:asa", "pan:traffic", "zeek_conn", "suricata", "WinEventLog:Security")
("EFCore Tutorial P4Cleaning Up OnModelCre")
| stats count earliest(_time) as first_seen latest(_time) as last_seen by src_ip, dest_ip, dest_host, signature
| eval first_seen=strftime(first_seen, "%Y-%m-%d %H:%M:%S"), last_seen=strftime(last_seen, "%Y-%m-%d %H:%M:%S")
| sort - count
Syntax validiert (0 Fehler)
message: "*EFCore Tutorial P4Cleaning Up OnModelCre*"
Syntax validiert (0 Fehler)
CommonSecurityLog
| where Message has "EFCore Tutorial P4Cleaning Up OnModelCre"
| summarize EventCount = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by SourceIP, DestinationIP, DestinationPort, Activity
| extend DetectionRule = "iShareStuff-CTI-Compiled"
| sort by EventCount desc

2. Cyber Threat Intelligence & Forensik

CTI Threat Relationship Graph2 Knoten / 1 Relationen
CVE / Incident Software MITRE ATT&CK CWE Weakness IoC
🎯
MITRE ATT&CK Matrix Navigator 14 Taktiken
Reconnaissance
-
Resource Development
-
Initial Access
Execution
Persistence
-
Privilege Escalation
Defense Evasion
Credential Access
-
Discovery
-
Lateral Movement
-
Collection
-
Command and Control
Exfiltration
-
Impact
tsecurity.de Cognitive Threat RAG
Fokus-Vektor:

Kognitive Analyse für identifizierte Bedrohung: Erhöhte Bedrohungslage im Bereich EFCore Tutorial P4:Cleaning Up `OnModelC.... Basierend auf 368k Vektor-Korrelationen werden sofortige Isolationsmaßnahmen für betroffene Endpunkte empfohlen.

🛡️ Angriffsfläche & Exposure

Netzwerk/Remote-Zugriff ohne Vorauthentifizierung möglich.

⚡ Empfohlene Sofortmaßnahmen
  • 1. Perimeter-Inspektion: Relevante Portfreigaben und exponierte Endpunkte unverzüglich scannen.
  • 2. Patch-Applikation: Hersteller-Hotfix einspielen oder betroffene Daemons in isolierte DMZ-Segmente überführen.
  • 3. Telemetrie & EDR-Alerts: Prozessaufrufe und Child-Processes auf anomale Shell-Spawns überwachen.
🔗 Semantisch verwandte Zero-Days MariaDB 11.7 VEC
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten EFCore Tutorial P4:Cleaning Up `OnModelCreating`

Thematisch verwandte Begriffe: EFCore, Tutorial, P4Cleaning, OnModelCreating · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-61525 | Zammad is a web based open source helpdesk/customer support system. In 7…
Advisory →
tsecurity.de Icon
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag