<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yahia Saafan on Medium]]></title>
        <description><![CDATA[Stories by Yahia Saafan on Medium]]></description>
        <link>https://medium.com/@yayasaafan?source=rss-a54035c59095------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ul6Ces5zn2MHjkuDfxxoMw.jpeg</url>
            <title>Stories by Yahia Saafan on Medium</title>
            <link>https://medium.com/@yayasaafan?source=rss-a54035c59095------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:43:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yayasaafan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Concept to Code: Building Background Jobs in ASP.NET Core with Hangfire]]></title>
            <link>https://medium.com/@yayasaafan/from-concept-to-code-building-background-jobs-in-asp-net-core-with-hangfire-d4a9d97b9004?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a9d97b9004</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[background-jobs]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[hangfire]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 11:27:46 GMT</pubDate>
            <atom:updated>2025-04-23T11:27:46.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Background Jobs" src="https://cdn-images-1.medium.com/max/932/1*Q9dQdAADwqmjeL-ei9a0-Q.png" /></figure><h3>Introduction:</h3><p>Imagine your app just confirmed a user’s payment. Now, it needs to send an invoice, notify the support team, update analytics, and log everything — fast. But you don’t want the user waiting around for all that to finish.</p><p>That’s where <strong>background jobs</strong> come in. They’re like quiet assistants working behind the scenes, taking care of heavy tasks after the user moves on.</p><p>In this guide, we’ll start by breaking down <strong>what background jobs are</strong>, <strong>why they matter</strong>, and <strong>how they work internally</strong>. Then, once you understand the big picture, we’ll dive into <strong>Hangfire</strong>, a powerful and developer-friendly .NET library that helps you implement background jobs reliably and with full visibility.</p><p>Whether you’re new to async processing or looking to scale your background workload like a pro, this article has something for you.</p><h3>What Exactly Is a Background Job?</h3><p>Think of a background job as a behind-the-scenes task — something your application does <em>after</em> it’s done talking to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17aaFjGt0CGGsukc_Kb-bQ.png" /><figcaption>Background Job</figcaption></figure><p>Instead of making the user wait while you send an email, crunch some analytics, or clean up old records, background jobs allow you to <strong>offload that work</strong> and run it <strong>asynchronously</strong>, <strong>independently</strong>, and often <strong>after the request is finished</strong>.</p><p>These jobs are not part of the web request/response cycle. That means they can:</p><ul><li>Kick off <strong>after</strong> the HTTP response is returned</li><li>Run on <strong>schedules</strong> (like every night at midnight)</li><li>Operate on <strong>background threads</strong>, in <strong>background services</strong>, or even on <strong>entirely separate servers</strong></li></ul><p>This is how modern apps stay fast, scalable, and responsive.</p><h3>The Lifecycle of a Background Job</h3><p>Let’s walk through what happens from the moment your code says, “Hey, I’ve got some background work,” to when that job is marked complete:</p><pre>→ Job Created (by user action or system trigger)<br>→ Job Enqueued (in memory or persistent storage)<br>→ Job Picked Up by Worker (polling in background)<br>→ Job Executed (task runs)<br>→ Job Completed (or fails → gets retried, logged, or marked failed)</pre><h4>Step 1: Creation — “I Have Work To Do”</h4><p>Everything starts when your app needs to do something, but not immediately.</p><p>For example, a user signs up on your website. You want to send them a welcome email, but sending it right now might slow things down. So instead, your app says, <strong>“I’ll let something else handle this later.”</strong></p><p>It adds the task to a <strong>waiting list</strong>. That task will be picked up by a background worker (a helper running in the background) when it’s ready to work on it.</p><p>You can think of it like placing an order at a coffee shop:</p><ul><li>You ask for a latte.</li><li>The barista writes it down and puts it in a queue.</li><li>While they’re making it, you can walk away or wait — your part is done.</li><li>Later, when it’s ready, they hand it to you.</li></ul><p>That’s exactly how background jobs work. Your app moves on quickly, and the task finishes in the background.</p><h4>Step 2: Storage — “Remember This Task, Even if We Crash”</h4><p>While some systems keep jobs in memory (fast but risky), most production-grade apps persist them to a <strong>reliable store</strong> like SQL Server, Redis.</p><p>This means:</p><ul><li>Jobs survive server restarts or crashes</li><li>You can distribute jobs across multiple machines</li><li>Failed jobs can be retried later</li></ul><p>It’s like saving your to-do list on the cloud instead of a piece of paper.</p><h4>Step 3: Processing — “A Worker Picks It Up”</h4><p>Now enters the <strong>worker</strong> — a background process (or service) that constantly checks the queue: “Any jobs for me?”</p><p>If it finds one, it grabs it, locks it, and gets ready to run it.</p><p>This worker might live <strong>inside your main app</strong> or be a <strong>dedicated process on another server</strong>. You can even run multiple workers in parallel for scale.</p><h4>Step 4: Execution — “Let’s Get It Done”</h4><p>This is where the real work happens. The worker executes the logic inside your job. Maybe it’s sending an email, creating a report, making an API call, or cleaning up old records in the database. You might use <strong>EF Core</strong>, access cloud services, or do some I/O operations — it’s your code, running in the background.</p><h4>Step 5: Completion — “All Done (or Maybe Not)”</h4><p>When the job finishes:</p><ul><li>It’s marked as “succeeded”.</li></ul><p>If it fails, it can:</p><ul><li>Be <strong>re-tried automatically</strong> (as per your config)</li><li>Be <strong>logged</strong> for inspection</li><li>Or be marked as <strong>failed</strong> and shown in your job dashboard</li></ul><p>Some systems also support smart retry strategies, like limiting retries to avoid abuse.</p><h3>Why This Matters?</h3><p>Background jobs <strong>decouple slow, non-critical operations from user interactions</strong>. This gives your app space to breathe and scale efficiently. But it also means you need to treat them like first-class citizens in your architecture — with visibility, error handling, and proper data access.</p><h3>How Background Jobs Are Stored, Picked, and Executed?</h3><h4>In-Memory Jobs (Quick but Risky)</h4><p>In the simplest setup, background jobs are just tasks kept <strong>in memory</strong>.</p><ul><li>Your app adds a job to a <strong>temporary list in RAM</strong></li><li>A background worker checks that list and runs the tasks</li></ul><p>It’s easy to set up, but if the app restarts or crashes, the jobs are <strong>gone forever</strong> — you can’t retry or recover them. This is fine for tiny apps or quick experiments, but it’s <strong>not safe for real-world systems</strong>.</p><h4>Persistent Jobs (The Reliable Way)</h4><p>In most real apps, jobs are <strong>saved in a database or a message queue</strong> (like SQL Server, Redis, or RabbitMQ).</p><ul><li>When you add a job, it’s stored in a <strong>safe place</strong></li><li>A background worker checks the database regularly for new jobs</li><li>It picks up the next job and runs it</li></ul><p>This setup is much better because:</p><ul><li>Jobs <strong>survive crashes or restarts</strong></li><li>You can <strong>retry failed jobs</strong></li><li>You can <strong>scale up</strong>, adding more workers to share the load</li></ul><p>It’s the professional, reliable way to run background jobs — especially in production.</p><h3>Do Background Jobs Use the Database?</h3><p>Yes, in two main ways:</p><h4>1. They Work With Your Data</h4><p>Jobs often need to <strong>read or update</strong> your app’s database.</p><p>For example:</p><ul><li>Clean up old or expired records</li><li>Generate a report from user data</li><li>Send a reminder for unpaid invoices</li></ul><p>So even though the job runs in the background, it still interacts with your app’s database just like normal code.</p><h4>2. They Live In the Database</h4><p>In many systems, such as Hangfire, background jobs are <strong>stored in the database</strong>, not just the results.</p><p>This means the database holds:</p><ul><li><strong>Info about the job</strong> (its name, type, when it was created)</li><li><strong>What it’s supposed to do</strong> (method name, arguments)</li><li><strong>Status and retries</strong> (whether it succeeded, failed, how many times it retried)</li></ul><p>This helps with tracking, retries, and job history. And it lets you manage jobs using a dashboard or admin panel.</p><h3>Using Dependency Injection (DI) in Background Jobs</h3><p>Yes, you can use <strong>Dependency Injection</strong> (DI) in background jobs, just like you do in your web controllers or services. But there’s one important difference you need to be aware of:</p><h4>Watch Out for Scoped Services</h4><p>In ASP.NET Core, services are registered with <strong>lifetimes</strong> — the most common one being scoped, which means:</p><ul><li>In a web app, a <strong>new instance</strong> of the service is created <strong>for each HTTP request</strong>.</li><li>But background jobs <strong>don’t have an HTTP request</strong>, so that lifecycle doesn’t apply automatically.</li></ul><p>If you try to use a scoped service directly in a background job, you might get strange behavior or even runtime errors.</p><h4>The Right Way: Create a Scope Manually</h4><p>To use scoped services (like DbContext) safely in a background job, you should <strong>manually create a service scope</strong> using IServiceScopeFactory. Here&#39;s how:</p><pre>using var scope = _scopeFactory.CreateScope();<br>var dbContext = scope.ServiceProvider.GetRequiredService&lt;MyDbContext&gt;();</pre><p>This gives you a fresh, clean instance of the service, just like if it were handling a real web request. And it ensures everything is disposed properly when the job finishes.</p><h3>Where Do Background Jobs Actually Run?</h3><p>Background jobs don’t always live inside your main web app. Depending on your needs and scale, they can be hosted in several different places:</p><h4>1. Inside Your Web App</h4><p>If you’re just getting started or building a small app, you can run background jobs directly inside your ASP.NET Core app using something like BackgroundService.</p><ul><li>Easy to set up</li><li>But less scalable, it can slow down your main app if jobs are heavy</li></ul><h4>2. In a Dedicated Worker App</h4><p>For more serious projects, it’s better to create a <strong>separate .NET Worker Service</strong> — a standalone app that runs background jobs full-time.</p><ul><li>It keeps job processing <strong>isolated</strong> from your web app</li><li>It lets you <strong>scale independently</strong> and avoid blocking HTTP traffic</li></ul><h4>3. In the Cloud (Serverless)</h4><p>You can also offload background jobs to <strong>cloud-hosted services</strong> like:</p><ul><li><strong>Azure Functions</strong></li><li><strong>AWS Lambda</strong></li><li><strong>Google Cloud Functions</strong></li></ul><p>These are great for <strong>pay-per-execution</strong> models and <strong>auto-scaling</strong>, especially if jobs are infrequent.</p><h4>4. With a Job Scheduler</h4><p>Libraries like <strong>Hangfire</strong> give you full control over:</p><ul><li>When jobs run (now, later, on a schedule)</li><li>How they’re stored and re-tried</li><li>How failures are logged or handled</li></ul><p>These tools usually come with a <strong>dashboard</strong>, <strong>database storage</strong>, and <strong>worker management</strong> built in, making them perfect for production use.</p><h3>From Concept to Code: Choosing the Right Tool</h3><p>Now that you have a solid understanding of how background jobs work under the hood, the next question is: <em>How do you actually implement all this in a .NET application?</em></p><p>There are a few options out there, but if you’re looking for something powerful, reliable, easy to use, and production-ready, there’s one tool that really stands out.</p><h3>Meet Hangfire: Background Jobs Made Simple for .NET</h3><p><strong>Hangfire</strong> is a powerful .NET library that makes it incredibly easy to run background tasks, without needing to reinvent the wheel.</p><p>It takes care of everything: <strong>queuing jobs</strong>, <strong>running them in the background</strong>, <strong>handling retries</strong>, and even giving you a <strong>web dashboard</strong> to track what’s happening.</p><p>Whether you need to:</p><ul><li>Send emails</li><li>Process data</li><li>Generate reports or PDFs</li><li>Call third-party APIs</li><li>Run scheduled tasks (like nightly cleanups)</li></ul><p>Hangfire has your back, with <strong>zero extra infrastructure</strong> needed.</p><h3>Why Use Hangfire?</h3><p>Here’s what makes Hangfire such a popular choice among .NET developers:</p><ul><li>It runs jobs <strong>outside the HTTP request</strong>, so your users aren’t stuck waiting.</li><li>It can <strong>retry failed jobs</strong> automatically — no extra code needed.</li><li>It comes with a built-in <strong>dashboard</strong> where you can see all jobs: succeeded, failed, pending, and more.</li><li>Jobs are saved in your <strong>database</strong>, so nothing is lost, even if the app crashes or restarts.</li></ul><h3>How Does Hangfire Work?</h3><p>The process is straightforward:</p><ol><li><strong>You enqueue a job</strong> — for example, “Send a welcome email”.</li><li>Hangfire <strong>stores the job</strong> in your database.</li><li>A <strong>background worker</strong> picks up the job.</li><li>Hangfire <strong>runs the job</strong> and <strong>tracks the result</strong>.</li></ol><p>You get full visibility in a dashboard, and you don’t have to worry about building retry logic, job tracking, or crash recovery yourself.</p><h3>Setting Up Hangfire in Your .NET App</h3><p>Now that you understand how Hangfire works, let’s see how to <strong>get it running in your project</strong>. The setup is straightforward and only takes a few steps.</p><h4>Step 1: Install the NuGet Packages</h4><p>Hangfire is available via NuGet. To get started, run these commands in your terminal:</p><pre>dotnet add package Hangfire.AspNetCore<br>dotnet add package Hangfire.SqlServer<br>dotnet add package Microsoft.Data.SqlClient</pre><p>This installs Hangfire along with the SQL Server integration and client library, which we’ll use to store job data in a database.</p><h4>Step 2: Configure Hangfire in Program.cs</h4><p>Next, open your Program.cs file and set up Hangfire inside your app’s startup pipeline.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Add Hangfire and tell it to use SQL Server for storage<br>builder.Services.AddHangfire(config =&gt;<br>    config.UseSqlServerStorage(&quot;ConnectionString&quot;));<br><br>// Add the Hangfire background job server<br>builder.Services.AddHangfireServer();<br><br>var app = builder.Build();<br><br>// Enable the Hangfire dashboard UI at /hangfire<br>app.UseHangfireDashboard();</pre><p>Once your app is running, you can open a browser and go to:</p><pre>http://localhost:portNumber/hangfire</pre><p>This built-in dashboard lets you <strong>see job statuses</strong>, check <strong>failures</strong>, track <strong>retries</strong>, and manage <strong>job servers</strong> in real time.</p><p><em>Hangfire will automatically create tables in your database, like </em><em>Hangfire.Job, </em><em>Hangfire.State, </em><em>Hangfire.Serverand others to track everything internally.</em></p><h4>Step 3: Enqueue Your First Job</h4><p>Let’s add a simple background job that just prints a message. You can put this anywhere in your controller or service:</p><pre>BackgroundJob.Enqueue(() =&gt; Console.WriteLine(&quot;Hello from background job!&quot;));</pre><p>That’s it! You’ve just created a <strong>fire-and-forget</strong> job that runs immediately in the background.</p><p>You’ll see it show up in the dashboard as soon as it runs, first in the <strong>“Enqueued”</strong> tab, then marked as <strong>“Succeeded”</strong> (or <strong>“Failed”</strong> if something goes wrong).</p><h3>Types of Background Jobs in Hangfire</h3><p>Hangfire supports different job types to cover a variety of real-world needs. Let’s walk through each one, when to use it, and how it behaves in the system.</p><h4>1. Fire-and-Forget Jobs</h4><p><strong>What it is:</strong><br>A job that runs immediately and only once. As soon as you enqueue it, Hangfire will process it in the background — no schedule, no delay.</p><p><strong>When to use it:</strong><br>Use this when you want to do something <em>after a user action</em>, but don’t want to make them wait.</p><p><strong>Example:</strong><br>Send a welcome email right after someone signs up.</p><p><strong>Code example:</strong></p><pre>BackgroundJob.Enqueue&lt;EmailService&gt;(email =&gt; email.SendWelcomeEmail(&quot;ahmed@example.com&quot;));</pre><p><strong>In the dashboard:</strong><br> You’ll see it appear under “Enqueued,” and then it moves to “Succeeded” or “Failed” depending on the outcome.</p><h4>2. Delayed Jobs</h4><p><strong>What it is:</strong><br>A job that runs only once, but <strong>after a specific delay</strong>, for example, 5 minutes or 24 hours later.</p><p><strong>When to use it:</strong><br>Perfect for reminder emails, cleanup tasks, or anything that needs to happen <em>later</em>, not right now.</p><p><strong>Example:</strong><br>Send a follow-up email one day after a user registers.</p><p><strong>Code example:</strong></p><pre>BackgroundJob.Schedule&lt;EmailService&gt;(<br>    email =&gt; email.SendFollowUpEmail(&quot;ahmed@example.com&quot;),<br>    TimeSpan.FromHours(24));</pre><p><strong>In the dashboard:</strong><br>You’ll find it in the “Scheduled” section. It moves to “Enqueued” once the delay passes, and then gets picked up by a worker.</p><h4>3. Recurring Jobs</h4><p><strong>What it is:</strong><br>A job that runs on a <strong>regular schedule</strong> — like every day, every hour, or once a week. You define the pattern using built-in or custom CRON expressions.</p><p><strong>When to use it:</strong><br>Use recurring jobs for things that happen on a fixed schedule: daily reports, system cleanups, backups, etc.</p><p><strong>Example:</strong><br>Clear out expired sessions every night at midnight.</p><p><strong>Code example:</strong></p><pre>RecurringJob.AddOrUpdate&lt;SessionService&gt;(<br>    &quot;cleanup-expired-sessions&quot;,<br>    service =&gt; service.CleanupExpiredSessions(),<br>    Cron.Daily);</pre><p><strong>More CRON options:</strong></p><ul><li>Cron.Minutely</li><li>Cron.Hourly</li><li>Cron.Weekly</li><li>Or your own expression (e.g., &quot;0 0 * * 1&quot; for Mondays at midnight)</li></ul><p><strong>In the dashboard:</strong><br>These show up in the “Recurring Jobs” tab, along with their last and next run times.</p><h4>What is a CRON expression?</h4><p>A <strong>CRON expression</strong> is a string made up of numbers and symbols that tells the system <strong>when to run something</strong>. It’s commonly used in schedulers like Hangfire or Unix-based systems.</p><p>Here’s a quick breakdown of this expression:</p><pre>&quot;0 0 * * 1&quot;</pre><p>It means:</p><ul><li>0 → minute (0th minute)</li><li>0 → hour (midnight)</li><li>* → every day of the month</li><li>* → every month</li><li>1 → only on <strong>Monday</strong></li></ul><p>So the full expression means: <strong>“Run every Monday at midnight.”</strong></p><h4>4. Continuation Jobs</h4><p><strong>What it is:</strong><br>A job that runs <strong>only after another job completes</strong>. You can use these to create job chains, where one task depends on the success of another.</p><p><strong>When to use it:</strong><br>Useful when you have steps that must happen in a specific order.</p><p><strong>Example:</strong><br>First, generate a PDF invoice, then send it by email.</p><p><strong>Code example:</strong></p><pre>var jobId = BackgroundJob.Enqueue&lt;InvoiceService&gt;(<br>    invoice =&gt; invoice.GenerateInvoice(123));<br>BackgroundJob.ContinueJobWith&lt;EmailService&gt;(jobId,<br>    email =&gt; email.SendInvoiceEmail(123));</pre><p><strong>In the dashboard:</strong><br>Continuation jobs are visibly linked to the original job and won’t run until the first one finishes successfully.</p><h3>Quick Recap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UfzUl1Owv3oUIuzwFQw5Q.png" /></figure><ul><li><strong>Fire-and-Forget:</strong> Run immediately. Great for simple background actions like sending emails.</li><li><strong>Delayed:</strong> Run after a delay. Useful for follow-ups or deferred processing.</li><li><strong>Recurring:</strong> Run on a schedule. Ideal for maintenance tasks or reporting.</li><li><strong>Continuation:</strong> Run after another job. Best for multi-step workflows.</li></ul><h3>Conclusion</h3><p>Background jobs are essential for building fast, scalable, and reliable applications, especially when you want to handle slow or non-critical tasks outside the user’s experience.</p><p>We explored how background jobs work conceptually, how they’re stored, triggered, and executed. From understanding where these jobs live to how they scale across environments, you now have the mental model to design background processing thoughtfully.</p><p>And with <strong>Hangfire</strong>, implementing all of this in a real .NET app becomes not just possible, but easy. You get retries, dashboards, scheduling, and job persistence — without writing your own infrastructure.</p><p>Whether you’re building a startup MVP or maintaining a large enterprise system, background jobs will help your app stay sharp, responsive, and reliable under load.</p><p>Now it’s your turn: explore the examples, experiment in your app, and start running tasks in the background like a pro.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a9d97b9004" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering EF Core Configuration: Part 7 — Value Conversion]]></title>
            <link>https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-7-value-conversion-9efb79547f8a?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/9efb79547f8a</guid>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 14:19:21 GMT</pubDate>
            <atom:updated>2024-10-13T14:19:21.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNo0jFvgvmOSnTELTxb9BQ.jpeg" /></figure><h3>Mastering EF Core Configuration: Part 7 — Value Conversion</h3><h3>Introduction</h3><p>In modern data-driven applications, flexibility in data storage is key. Often, the way data is represented in your application differs from how it needs to be stored in the database. This is where Entity Framework Core (EF Core) comes to the rescue with its powerful <strong>Value Conversions</strong> feature. Value conversions allow you to seamlessly transform data between your .NET model and the underlying database format, opening up a world of possibilities — whether it’s converting enums, encrypting sensitive information, or handling custom data types.</p><p>In this story, we will explore the ins and outs of value conversions in EF Core. We will cover practical scenarios like converting enums to strings, encrypting sensitive data, and even applying more advanced custom converters. These examples will demonstrate how to make your application’s data storage both secure and efficient, while keeping your models clean.</p><h3>When to Use Value Conversions?</h3><p>Now that we’ve set the stage with a solid understanding of what value conversions are, let’s dive a little deeper. Because here’s the thing — before you start applying value conversions everywhere, you need to know <strong>when</strong> they truly shine. Not every situation calls for them, but when the moment is right, they can become your secret weapon in shaping how your data is stored.</p><p>Picture this: You’re working with a status system for users, where each user can be either active, inactive, or suspended. In your code, you’ve set this up as an enum. But when it comes to the database, things work differently. By default, EF Core will store the enum as an integer, but not very human-friendly if you ever need to look at the data directly. What if you’d rather store it as a string, so it reads “Active” instead of “1”? That’s where value conversions come in, allowing you to tailor how your enums are stored and retrieved.</p><p>Or imagine you’re dealing with sensitive data — personal information like Social Security Numbers, credit card details, or anything you want to keep under lock and key. Instead of storing that data in plain text, value conversions let you encrypt it before it ever touches the database. Secure, right?</p><p>And it’s not just about security or enums. Think about custom data types — something like a DateTimeOffset. Your app handles time zones perfectly, but the database doesn’t quite get it. Instead of overhauling your data model, value conversions step in to convert the DateTimeOffset to a plain DateTime, saving you a world of compatibility headaches.</p><p>Finally, let’s talk about formatting. Maybe you want to store numbers or strings in a specific way — perhaps stripping out special characters or formatting them in a standard way before saving. With value conversions, you get to decide exactly how that formatting happens, ensuring that your database always receives data in the cleanest, most consistent format possible.</p><p>And just to keep things crystal clear, here are some of the top scenarios where value conversions shine:</p><ul><li><strong>Enum to String/Integer</strong>: Converting an enum to a string or integer for storage in the database.</li><li><strong>Encrypting Data</strong>: Encrypting sensitive data before storing it in the database.</li><li><strong>Custom Types</strong>: Converting complex or custom types to a format that the database can store, such as converting a DateTimeOffset to DateTime.</li><li><strong>Formatting</strong>: Applying specific formatting to strings or numbers before saving them.</li></ul><h3>Basic Example: Enum to String Conversion</h3><p>Alright, so now that we’ve seen when value conversions are useful, let’s get our hands dirty with a basic example. Imagine this: You’re building a user management system, and each user has a status — maybe they’re active, inactive, or suspended. In your code, you’ve set this up as an enum because it’s clean, intuitive, and ensures that only valid statuses are used.</p><p>So, you have something like this:</p><pre>public enum Status<br>{<br>    Active,<br>    Inactive,<br>    Suspended<br>}<br><br>public class User<br>{<br>    public int UserId { get; set; }<br>    public string Name { get; set; }<br>    public Status UserStatus { get; set; }<br>}</pre><p>Simple enough, right? But here’s the twist: By default, EF Core is going to store that Status enum as an integer in your database. Now, if you or anyone else is looking directly at the database tables, seeing 1 or 2 as a user’s status isn’t exactly readable. Wouldn’t it be better if it said “Active” or “Suspended” instead? Much clearer. This is where value conversions come into play.</p><p>So, let’s tell EF Core to store the enum as a string, making everything more human-readable.</p><h4>Configuring the Value Conversion</h4><p>Here’s how you do it. Using the Fluent API in the OnModelCreating method, we can configure the value conversion:</p><pre>public class ApplicationDbContext : DbContext<br>{<br>  public DbSet&lt;User&gt; Users { get; set; }<br><br>  protected override void OnModelCreating(ModelBuilder modelBuilder)<br>  {<br>    modelBuilder.Entity&lt;User&gt;()<br>      .Property(u =&gt; u.UserStatus)<br>      .HasConversion(<br>        // Converts the enum to string when saving to the database<br>        v =&gt; v.ToString(),<br>        // Converts the string back to enum when reading from the database<br>        v =&gt; (Status)Enum.Parse(typeof(Status), v)<br>      );<br>  }<br>}</pre><p>Let me break this down for you. We’re using the <strong>HasConversion </strong>method, which is the hero of this transformation. It takes two functions:</p><ol><li><strong>Saving to the Database</strong>: The first function converts the enum to a string. So when you’re saving a user’s status, instead of storing 1 for &quot;Active&quot; or 2 for &quot;Suspended,&quot; it stores the string version, like “Active” or “Suspended.”</li><li><strong>Reading from the Database</strong>: The second function works in reverse. When you retrieve that user from the database, EF Core takes the string value (“Active,” for example) and converts it back into the enum (Status.Active).</li></ol><p>That’s it! This simple conversion ensures that your database stays readable and consistent, while your application code still benefits from the safety and structure that enums provide.</p><h3>More Complex Example: Encrypting and Decrypting Data</h3><p>Now, things are about to get a little more serious. Imagine you’re dealing with sensitive data — like Social Security Numbers (SSN) or credit card information. Storing this kind of data in plain text is risky, especially with today’s security concerns. But don’t worry, value conversions are here to help once again, this time to ensure your sensitive information is safely encrypted before it ever hits the database.</p><p>Let’s take a look at a real-world scenario. You’ve got a Person entity, and you need to store their SSN. Obviously, you don’t want this sitting in your database for anyone to see. Instead, we’ll encrypt the SSN before storing it and decrypt it when we need to access it.</p><p>Here’s how it works:</p><pre>public class Person<br>{<br>    public int PersonId { get; set; }<br>    public string Name { get; set; }<br>    public string EncryptedSSN { get; set; }<br>}</pre><p>Now, the key part is making sure that the EncryptedSSN is securely handled. This is where you bring in an Encryptor class—a simple utility that handles both the encryption and decryption of the SSN. Think of it as a personal bodyguard for your data.</p><p>So, let’s see how to apply this using EF Core’s value conversions:</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Person&gt; People { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        var encryptor = new Encryptor(); // Your encryption service<br>        modelBuilder.Entity&lt;Person&gt;()<br>            .Property(p =&gt; p.EncryptedSSN)<br>            .HasConversion(<br>              // Encrypt the SSN before saving to the database<br>                v =&gt; encryptor.Encrypt(v),<br>              // Decrypt the SSN when retrieving it from the database<br>                v =&gt; encryptor.Decrypt(v)<br>            );<br>    }<br>}</pre><p>Let’s break that down:</p><ol><li><strong>Saving the SSN</strong>: When a person’s data is being saved, the HasConversion method encrypts the SSN before it ever touches the database. That way, all that gets stored is the encrypted, <strong>unreadable</strong> version of the SSN.</li><li><strong>Retrieving the SSN</strong>: When you need to retrieve a person’s SSN, the same HasConversion method decrypts the data. So when the application reads the encrypted SSN from the database, it is automatically decrypted into its original form.</li></ol><p>This approach ensures that sensitive information like an SSN never exists in plain text within your database — an essential step for protecting personal data in any modern application.</p><h3>Using Custom Value Converters</h3><p>Now, let’s take things a step further. In the last example, we saw how to encrypt and decrypt data using EF Core’s built-in value converters. But what if your application needs something even more customized — something that goes beyond what the default converters can handle? This is where <strong>custom value converters</strong> come in. Once you start using them, they’ll quickly become one of your go-to tools in the EF Core toolkit.</p><p>Imagine you’re working with data that requires a little more attention, like sensitive strings that need encryption before they hit the database. Maybe you need to compress large text fields or transform complex types. With custom value converters, you have the power to define how EF Core should handle these transformations, giving you complete control over your data flow.</p><h3>Creating a Custom Value Converter</h3><p>The beauty of custom value converters lies in their flexibility. To create one, you define a class that inherits from ValueConverter&lt;TModel, TProvider&gt;. Sounds technical? Let’s break it down:</p><ul><li><strong>TModel</strong>: This is the type of property in your model class — essentially the type you’re working with within your .NET code.</li><li><strong>TProvider</strong>: This is the type that will be stored in your database — how the data looks once it’s saved.</li></ul><h3>Example: Encrypting and Decrypting a String</h3><p>As we mentioned earlier, we’ve already seen how to handle Social Security Number (SSN) encryption using a simple value conversion method. But now, let’s take it a step further and show you how to achieve the same thing using a <strong>custom converter</strong>. This time, we’ll build it step by step, giving you even more control and flexibility in how your data is transformed.</p><h4>Step 1: Create the Encryptor Class</h4><p>Before we create the converter, we need a way to actually encrypt and decrypt our data. Here’s a simple Encryptor class that demonstrates the concept:</p><pre>public class Encryptor<br>{<br>    private readonly string key = &quot;encryptionkey&quot;; // Simplified example key<br><br>    public string Encrypt(string value)<br>    {<br>        if (string.IsNullOrEmpty(value)) return value;<br>        // Add encryption logic here<br>        return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value + key));<br>    }<br>    public string Decrypt(string value)<br>    {<br>        if (string.IsNullOrEmpty(value)) return value;<br>        // Add decryption logic here<br>        var base64EncodedBytes = Convert.FromBase64String(value);<br>        return System.Text.Encoding.UTF8.GetString(base64EncodedBytes)<br>                .Replace(key, string.Empty);<br>    }<br>}</pre><p>This Encryptor class is responsible for the encryption and decryption logic. Of course, in a real-world application, encryption would be more robust, but for now, this gets the job done.</p><h4>Step 2: Define the Custom Value Converter</h4><p>With our encryption mechanism in place, we can now define a custom value converter. The converter uses the Encryptor to handle the encryption and decryption of the SSN:</p><pre>public class EncryptedStringConverter : ValueConverter&lt;string, string&gt;<br>{<br>    private static readonly Encryptor _encryptor = new Encryptor();<br><br>    public EncryptedStringConverter()<br>        : base(<br>            // Convert to provider type (encrypt)<br>            v =&gt; _encryptor.Encrypt(v),<br>            // Convert to model type (decrypt)<br>            v =&gt; _encryptor.Decrypt(v)<br>        )<br>    {<br>    }<br>}</pre><p>Here’s how it works:</p><ul><li>When saving the data, the Encrypt method is called, converting the plain SSN into an encrypted string.</li><li>When retrieving the data, the Decrypt method kicks in, turning the encrypted string back into a readable SSN.</li></ul><h4>Step 3: Apply the Custom Value Converter</h4><p>Now that we have our converter, the final step is to tell EF Core to use it when working with the Person entity. We do this in the OnModelCreating method of our DbContext:</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Person&gt; People { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Person&gt;()<br>            .Property(p =&gt; p.EncryptedSSN)<br>            .HasConversion(new EncryptedStringConverter());<br>    }<br>}<br><br>public class Person<br>{<br>    public int PersonId { get; set; }<br>    public string Name { get; set; }<br>    public string EncryptedSSN { get; set; }<br>}</pre><p>With this setup:</p><ul><li>EF Core will automatically encrypt the SSN when saving a Person record.</li><li>It will automatically decrypt the SSN when retrieving the data, so you never have to worry about manually handling encryption in your application code.</li></ul><h3>Benefits of Custom Value Converters</h3><p>Now, let’s pause for a moment and talk about why custom value converters are so powerful:</p><ol><li><strong>Reuse Across Properties</strong>: Once you’ve created a custom converter, you can reuse it across different properties or even different entities. For example, if you need to encrypt other sensitive data like passwords or credit card details, the same converter can be applied.</li><li><strong>Encapsulation of Logic</strong>: All of the conversion logic — whether it’s encryption, formatting, or something else — is neatly encapsulated in the converter class. This keeps your models clean and focused on the domain logic while offloading the data transformation elsewhere.</li><li><strong>Clean Model Classes</strong>: Since the conversion logic is abstracted away, your model classes remain easy to read and understand, which is especially important in large applications where simplicity and clarity are key.</li></ol><h3>Common Use Cases</h3><p>Custom value converters are not just for encryption. Here are a few other scenarios where they can shine:</p><ul><li><strong>Encryption/Decryption</strong>: Encrypting sensitive information like Social Security Numbers, passwords, or credit card details before storing them.</li><li><strong>Compression/Decompression</strong>: If you have large text fields, like documents or logs, you can compress them before saving and decompress them when reading, which can save significant storage space.</li><li><strong>Format Conversion</strong>: You might need to convert data between different formats, such as converting a JSON string to an object and vice versa. A custom value converter allows you to handle that transformation smoothly.</li></ul><h3>Conclusion</h3><p>In summary, value conversions in EF Core offer a flexible and powerful way to manage how your data is stored and retrieved, from simple enum transformations to advanced encryption. Whether you’re using built-in converters or creating custom ones, these tools allow you to control how your application interacts with the database while keeping your models clean and efficient. By mastering these techniques, you can handle both everyday and complex scenarios with ease, ensuring your data is secure, readable, and perfectly tailored to your needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9efb79547f8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering EF Core Configuration: Part 6 — Owned Value Types]]></title>
            <link>https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-6-owned-value-types-0e536cb97a99?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e536cb97a99</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 13:28:47 GMT</pubDate>
            <atom:updated>2024-09-29T13:28:47.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRtztscPC1_UTLPKu7Yorw.jpeg" /><figcaption>Owned Value Types (Generated by AI)</figcaption></figure><h3>Mastering EF Core Configuration: Part 6 — Owned Value Types</h3><h3>Introduction</h3><p>In the previous article, we explored how to map database views in Entity Framework Core (EF Core), allowing us to retrieve data from views in a way that integrates seamlessly with our entity models “<a href="https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-5-mapping-views-2c44dc8a0083">Mastering EF Core Configuration: Part 5 — Mapping Views</a>”. Now, let’s shift our focus to another powerful feature in EF Core: <strong>Owned Entities</strong>. While mapping views helps us work with pre-defined, read-only datasets, owned entities allow us to break down complex data structures within a single entity and store them more modularly. In this article, we’ll dive into the concept of owned entities, understanding how they work, how to configure them, and why they are useful for creating cleaner and more maintainable data models.</p><h3>What Are Owned Entities?</h3><p>An <strong>Owned Entity</strong> in Entity Framework Core is a special kind of entity that exists solely as part of another entity. Rather than having its own identity (like a primary key), it shares the same identity as the entity it belongs to. In terms of database structure, <strong>fields of the owned entity are stored in the same table as the owning entity</strong>, with their columns prefixed by the name of the owned entity. This approach helps keep the model modular and precise by grouping related fields into a separate class, but without creating an entirely separate table in the database. For example, a Customer entity may have an Address as an owned entity, allowing the address fields (like Street, City, and PostalCode) to be stored in the Customer table while keeping the code organized and more maintainable.</p><h3>Key Characteristics of Owned Entities</h3><ol><li><strong>No Separate Identity</strong>: Owned entities do not have their own primary key; instead, they share the primary key of the entity that owns them. This means they cannot exist without the owning entity.</li><li><strong>Encapsulation</strong>: Owned entities are often used to encapsulate complex data structures within an entity. <strong>For example</strong>, you might use an owned entity to represent an address within a customer entity.</li><li><strong>Value Object Modeling</strong>: Owned entities are well-suited for modeling value objects in DDD, where the focus is on the attributes of the object rather than on its identity.</li><li><strong>Same Lifecycle</strong>: Owned entities share the lifecycle of their owning entity. When the owning entity is deleted, the owned entity is deleted as well.</li></ol><h3>Configuring Owned Entities in EF Core</h3><p>Consider a scenario where you have a Customer entity that includes an Address. You can model the Address as an owned entity because it does not have its own identity outside of the Customer.</p><h4><strong>Entity Definitions</strong>:</h4><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br>    // Navigation property for the owned entity<br>    public Address Address { get; set; }<br>}<br><br>[Owned]<br>public class Address<br>{<br>    public string Street { get; set; }<br>    public string City { get; set; }<br>    public string PostalCode { get; set; }<br>}</pre><ul><li><strong>[Owned] Attribute</strong>: The Address class is marked with the [Owned] attribute, indicating that it is an owned entity.</li><li><strong>Navigation Property</strong>: The Customer entity has a navigation property to the Address, but Address does not have its own primary key; it relies on the Customer&#39;s primary key.</li></ul><h4>Configuring Owned Entities Using <strong>Fluent API</strong>:</h4><p>You can configure owned entities using the Fluent API in the OnModelCreating method.</p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Customer&gt;()<br>        .OwnsOne(c =&gt; c.Address);<br>}</pre><ul><li><strong>modelBuilder.Entity&lt;Customer&gt;()</strong>: This line begins the configuration for the Customer entity. It tells EF Core that we want to customize how Customer is mapped to the database.</li><li><strong>.OwnsOne(c =&gt; c.Address)</strong>: The OwnsOne method is used to specify that Address is an owned entity. The lambda expression c =&gt; c.Address identifies the Address property within the Customer entity. An owned entity shares the primary key and lifecycle of its owning entity (Customer in this case), meaning when the Customer is inserted, updated, or deleted, the Address will be handled accordingly without separate tracking or identity.</li></ul><h4><strong>Complex Types</strong>:</h4><p>Owned entities can also represent more complex types, such as collections. When you have a collection of a class marked as an owned entity in Entity Framework Core (EF Core), the owned entities in the collection are typically stored in a separate table in the database. This approach allows EF Core to model the one-to-many relationship between the owning entity and the owned entity collection.</p><pre>public class Order<br>{<br>    public int OrderId { get; set; }<br>    public string ProductName { get; set; }<br>    // Collection of owned entities<br>    public ICollection&lt;OrderItem&gt; Items { get; set; }<br>}<br><br>[Owned]<br>public class OrderItem<br>{<br>    public string ItemName { get; set; }<br>    public int Quantity { get; set; }<br>}</pre><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Order&gt;()<br>    .OwnsMany(o =&gt; o.Items);<br>}</pre><ul><li><strong>modelBuilder.Entity&lt;Order&gt;()</strong>: This line starts the configuration for the Order entity.</li><li><strong>.OwnsMany(o =&gt; o.Items)</strong>: The OwnsMany method specifies that the Order entity owns a collection of OrderItem entities. The lambda expression o =&gt; o.Items refers to the Items collection within the Order entity. This means each OrderItem in the Items collection is treated as an owned entity. Owned entities don&#39;t have independent identity and are stored in a separate table, but they still share the lifecycle of the owning Order entity (e.g., when the Order is deleted, all associated OrderItem records are deleted as well).</li></ul><h3>Default Naming Convention</h3><p>For example, if you have an Address class as an owned entity within a Customer entity:</p><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br>    public Address Address { get; set; }<br>}<br><br>[Owned]<br>public class Address<br>{<br>    public string Street { get; set; }<br>    public string City { get; set; }<br>    public string PostalCode { get; set; }<br>}</pre><p>By default, EF Core will create columns named <strong>Address_Street</strong>, <strong>Address_City</strong>, and <strong>Address_PostalCode </strong>in the <strong>Customers</strong> table.</p><h3>Configuring Property Names Using Fluent API</h3><p>If you want to customize the column names of the properties in the owned entity, you can do so using the Fluent API in the OnModelCreating method. Here&#39;s how you can configure the column names:</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br><br>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Customer&gt;()<br>            .OwnsOne(c =&gt; c.Address, address =&gt;<br>            {<br>                address.Property(a =&gt; a.Street).HasColumnName(&quot;StreetName&quot;);<br>                address.Property(a =&gt; a.City).HasColumnName(&quot;CityName&quot;);<br>                address.Property(a =&gt; a.PostalCode).HasColumnName(&quot;PostalCodeValue&quot;);<br>            });<br>    }<br>}</pre><ul><li><strong>OwnsOne Method</strong>: This is used to configure an owned entity. The first argument is the navigation property in the owner entity (c =&gt; c.Address in this case).</li><li><strong>address.Property</strong>: Inside the configuration block, you can customize each property of the owned entity. The HasColumnName method specifies the name of the column in the database table.</li></ul><p>With this configuration, the columns in the Customers table will be named <strong>StreetName</strong>, <strong>CityName</strong>, and <strong>PostalCodeValue </strong>instead of the default Address_Street, Address_City, and Address_PostalCode.</p><h3>Example Scenario: Combining Owned Entities</h3><p>Let’s consider an example where you have a Customer entity that owns two different value objects: Address and ContactInfo. Each of these value objects could be modeled as owned entities.</p><h4>1. Defining the Entities:</h4><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br>    public Address Address { get; set; }<br>    public ContactInfo ContactInfo { get; set; }<br>}<br><br>[Owned]<br>public class Address<br>{<br>    public string Street { get; set; }<br>    public string City { get; set; }<br>    public string PostalCode { get; set; }<br>}<br><br>[Owned]<br>public class ContactInfo<br>{<br>    public string Email { get; set; }<br>    public string PhoneNumber { get; set; }<br>}</pre><ul><li><strong>Customer</strong>: The parent entity that owns both Address and ContactInfo.</li><li><strong>Address</strong>: An owned entity that contains address-related fields.</li><li><strong>ContactInfo</strong>: Another owned entity that contains contact-related fields.</li></ul><h4>2. Configuring Combined Owned Entities:</h4><p>In the OnModelCreating method, you can configure these owned entities to control how they are mapped to the database:</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Customer&gt;()<br>            .OwnsOne(c =&gt; c.Address, address =&gt;<br>            {<br>                address.Property(a =&gt; a.Street).HasColumnName(&quot;Street&quot;);<br>                address.Property(a =&gt; a.City).HasColumnName(&quot;City&quot;);<br>                address.Property(a =&gt; a.PostalCode).HasColumnName(&quot;PostalCode&quot;);<br>            });<br><br>        modelBuilder.Entity&lt;Customer&gt;()<br>            .OwnsOne(c =&gt; c.ContactInfo, contactInfo =&gt;<br>            {<br>                contactInfo.Property(c =&gt; c.Email).HasColumnName(&quot;Email&quot;);<br>                contactInfo.Property(c =&gt; c.PhoneNumber).HasColumnName(&quot;PhoneNumber&quot;);<br>            });<br>    }<br>}</pre><h4>How This Maps to the Database?</h4><ul><li><strong>Single Table</strong>: EF Core will map both the Address and ContactInfo properties of Customer to the Customers table. The properties of Address and ContactInfo will be columns in the same table.</li><li><strong>Column Naming</strong>: The HasColumnName method is used to customize the column names. If you don’t specify a custom name, EF Core will use a default naming convention like Address_Street or ContactInfo_Email as we said.</li></ul><h3>Nested Owned Entities</h3><p>Owned entities can also be nested within each other. For example, if Address itself had an owned entity like Coordinates (for latitude and longitude), you could configure this as well:</p><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br>    public Address Address { get; set; }<br>    public ContactInfo ContactInfo { get; set; }<br>}<br><br>[Owned]<br>public class Address<br>{<br>    public string Street { get; set; }<br>    public string City { get; set; }<br>    public string PostalCode { get; set; }<br>    public Coordinates Coordinates { get; set; }<br>}<br><br>[Owned]<br>public class Coordinates<br>{<br>    public double Latitude { get; set; }<br>    public double Longitude { get; set; }<br>}<br><br><br>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Customer&gt;()<br>            .OwnsOne(c =&gt; c.Address, address =&gt;<br>            {<br>                address.Property(a =&gt; a.Street).HasColumnName(&quot;Street&quot;);<br>                address.Property(a =&gt; a.City).HasColumnName(&quot;City&quot;);<br>                address.Property(a =&gt; a.PostalCode).HasColumnName(&quot;PostalCode&quot;);<br><br>                // Configuring nested owned entity<br>                address.OwnsOne(a =&gt; a.Coordinates, coordinates =&gt;<br>                {<br>                    coordinates.Property(c =&gt; c.Latitude).HasColumnName(&quot;Latitude&quot;);<br>                    coordinates.Property(c =&gt; c.Longitude).HasColumnName(&quot;Longitude&quot;);<br>                });<br>            });<br><br>        modelBuilder.Entity&lt;Customer&gt;()<br>            .OwnsOne(c =&gt; c.ContactInfo, contactInfo =&gt;<br>            {<br>                contactInfo.Property(c =&gt; c.Email).HasColumnName(&quot;Email&quot;);<br>                contactInfo.Property(c =&gt; c.PhoneNumber).HasColumnName(&quot;PhoneNumber&quot;);<br>            });<br>    }<br>}</pre><h3>Example Scenario: A Customer with a Collection of Addresses</h3><p>Suppose you have a Customer entity that can have multiple Address entities associated with it.</p><h4>1. Defining the Entities:</h4><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br><br>    // Collection of owned entities<br>    public ICollection&lt;Address&gt; Addresses { get; set; }<br>}<br><br>[Owned]<br>public class Address<br>{<br>    public int Id { get; set; } // Explicitly defined primary key<br>    public string Street { get; set; }<br>    public string City { get; set; }<br>    public string PostalCode { get; set; }<br>}</pre><h4>2. Configuring the Collection of Owned Entities</h4><p>To configure the collection of owned entities using the Fluent API, you can use the OwnsMany method in the OnModelCreating method:</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Customer&gt;()<br>            .OwnsMany(c =&gt; c.Addresses, address =&gt;<br>            {<br>		// Foreign key to the owning entity<br>                address.WithOwner().HasForeignKey(&quot;CustomerId&quot;);<br>                address.HasKey(a =&gt; a.Id);<br>                address.Property(a =&gt; a.Street).HasColumnName(&quot;Street&quot;);<br>                address.Property(a =&gt; a.City).HasColumnName(&quot;City&quot;);<br>                address.Property(a =&gt; a.PostalCode).HasColumnName(&quot;PostalCode&quot;);<br>            });<br>    }<br>}</pre><ul><li><strong>OwnsMany Method</strong>: This is used to configure a collection of owned entities. The first argument is the navigation property in the owner entity (c =&gt; c.Addresses).</li><li><strong>WithOwner</strong>: Specifies that the Address entities are owned by the Customer entity. The HasForeignKey method sets up the foreign key relationship.</li><li><strong>Column Configuration</strong>: You can customize the names of the columns using HasColumnName.</li></ul><h4>How EF Core Translates This to the Database?</h4><ul><li><strong>Separate Table for Owned Entities</strong>: EF Core will create a separate table for the Address collection because it cannot store a collection directly in the same table as the Customer. The table for the owned entities will typically have a foreign key pointing back to the Customer table to establish the relationship.</li><li><strong>Default Naming Convention</strong>: The table for the owned entities will have a name derived from the owning entity (e.g., Customer) and the owned entity (e.g., Address). The columns will include a foreign key to the Customer table (e.g., CustomerId) along with the properties of the owned entity.</li></ul><h4>Database Structure</h4><p>After configuring the above, the database will have two tables:</p><h4><strong>Customers Table</strong>:</h4><ul><li>CustomerId (Primary Key)</li><li>Name</li></ul><h4><strong>Addresses Table</strong>:</h4><ul><li>Id (Primary Key for Address)</li><li>CustomerId (Foreign Key pointing to Customers table)</li><li>Street</li><li>City</li><li>PostalCode</li></ul><h4>Example of Inserting Data</h4><p>When you insert a Customer with multiple Addresses, EF Core will automatically manage the relationship and insert the corresponding records into the Addresses table:</p><pre>using (var context = new ApplicationDbContext())<br>{<br>    var customer = new Customer<br>    {<br>        Name = &quot;John Doe&quot;,<br>        Addresses = new List&lt;Address&gt;<br>        {<br>            new Address { Street = &quot;123 Main St&quot;, City = &quot;Anytown&quot;, PostalCode = &quot;12345&quot; },<br>            new Address { Street = &quot;456 Oak St&quot;, City = &quot;Othertown&quot;, PostalCode = &quot;67890&quot; }<br>        }<br>    };<br><br>    context.Customers.Add(customer);<br>    context.SaveChanges();<br>}</pre><ul><li><strong>Automatic Handling</strong>: EF Core will insert the Customer into the Customers table and each Address into the Addresses table, linking them via the CustomerId foreign key.</li></ul><p>In Entity Framework Core (EF Core), you can indeed define the foreign key (FK) as a property in your owned entity class. However, when you do this, you typically also need to include a navigation property back to the owning entity (in this case, from Address to Customer). This setup is often used when you want the owned entity to be aware of its owning entity, which can be useful for certain types of queries or logic in your application.</p><h4>Defining Foreign Key and Navigation Property:</h4><p>Let’s modify the Address class to include a foreign key (CustomerId) and a navigation property back to the Customer entity:</p><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br><br>    // Collection of owned entities<br>    public ICollection&lt;Address&gt; Addresses { get; set; }<br>}<br><br>[Owned]<br>public class Address<br>{<br>    public int Id { get; set; }  // Primary key for Address<br>    public string Street { get; set; }<br>    public string City { get; set; }<br>    public string PostalCode { get; set; }<br><br>    // Foreign key to the Customer entity<br>    public int CustomerId { get; set; }<br>    // Navigation property back to Customer<br>    public Customer Customer { get; set; }<br>}</pre><h4>Configuring the Foreign Key and Navigation Property</h4><p>When you define a foreign key and navigation property in the owned entity, your Fluent API configuration would look like this:</p><pre>public class ApplicationDbContext : DbContext<br>{<br>  public DbSet&lt;Customer&gt; Customers { get; set; }<br><br>  protected override void OnModelCreating(ModelBuilder modelBuilder)<br>  {<br>    modelBuilder.Entity&lt;Customer&gt;()<br>        .OwnsMany(c =&gt; c.Addresses, address =&gt;<br>        {<br>          address.WithOwner(a =&gt; a.Customer) // Define navigation property<br>             .HasForeignKey(a =&gt; a.CustomerId);  // Define FK explicitly<br>          address.HasKey(a =&gt; a.Id);  // Define the primary key<br>          address.Property(a =&gt; a.Street).HasColumnName(&quot;Street&quot;);<br>          address.Property(a =&gt; a.City).HasColumnName(&quot;City&quot;);<br>          address.Property(a =&gt; a.PostalCode).HasColumnName(&quot;PostalCode&quot;);<br>        });<br>  }<br>}</pre><ul><li><strong>Foreign Key Property:</strong> CustomerId is explicitly defined as a property in the Address class. This property will store the foreign key value that links the Address to the Customer.</li><li><strong>Navigation Property:</strong> The Customer property in Address is a navigation property that allows EF Core to navigate from an Address back to the Customer it belongs to.</li><li><strong>WithOwner(a =&gt; a.Customer)</strong>: This method specifies that the Address entity is owned by Customer, and the Customer navigation property is used to define the relationship.</li><li><strong>HasForeignKey(a =&gt; a.CustomerId)</strong>: This method explicitly sets CustomerId as the foreign key.</li></ul><h3>Database Structure</h3><p>With this setup, the database will have two tables:</p><h4><strong>Customers Table</strong>:</h4><ul><li>CustomerId (Primary Key)</li><li>Name</li></ul><h4><strong>Addresses Table</strong>:</h4><ul><li>Id (Primary Key for Address)</li><li>CustomerId (Foreign Key to Customers table)</li><li>Street</li><li>City</li><li>PostalCode</li></ul><h3>Benefits of This Approach</h3><ol><li><strong>Clear Relationship Definition</strong>: The relationship between Customer and Address is clearly defined, with explicit foreign key and navigation properties, making the code easier to understand.</li><li><strong>Query Flexibility</strong>: You can easily navigate from an Address to its Customer and vice versa, allowing for more flexible and intuitive querying.</li></ol><h3>Benefits of Using Owned Entities</h3><ol><li><strong>Encapsulation</strong>: Owned entities allow you to encapsulate complex data structures within an entity, keeping your domain model clean and focused.</li><li><strong>Simplified Queries</strong>: Since owned entities are part of the same table as their owner, queries are simpler and can perform better.</li><li><strong>Consistency</strong>: Owned entities share the same lifecycle as their owner, ensuring consistency in your data model.</li></ol><h3>Conclusion</h3><p>As we conclude our journey through the world of EF Core and the concept of owned entities, we see how this powerful feature brings clarity and precision to our data models. By encapsulating related properties within a single entity and eliminating the need for separate tables, owned entities allow us to keep our domain models clean and focused while simplifying database structures and queries. Whether modeling value objects, handling complex types, or managing nested and collection-based ownership, EF Core’s owned entities provide a flexible and efficient way to shape our data without the overhead of additional identity management.</p><p>In the end, it’s all about balance — striking the right harmony between simplicity and power in your data design. Just as a master craftsman finds the perfect tool for each task, understanding when and how to use owned entities can unlock new levels of elegance in your EF Core applications. So, as you move forward, keep this tool in your toolkit, ready to shape the next layer of your application’s data architecture with precision and grace.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e536cb97a99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering EF Core Configuration: Part 5 — Mapping Views]]></title>
            <link>https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-5-mapping-views-2c44dc8a0083?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c44dc8a0083</guid>
            <category><![CDATA[database-view]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ef-core]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 10:12:25 GMT</pubDate>
            <atom:updated>2024-09-17T10:12:25.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*GyR8ugetoFRQFfR-yj8eBw.png" /></figure><h3>Mastering EF Core Configuration: Part 5 — Mapping Views</h3><h3>Introduction</h3><p>In most applications, views are an essential database feature that allow you to encapsulate complex queries and join multiple tables, presenting a simplified, read-only dataset to the application layer. They offer a clean way to manage and retrieve data without exposing the underlying complexity of the database schema.</p><p>In this guide, we’ll dive into <strong>how you can map a database view in Entity Framework Core (EF Core)</strong>, making it easier to interact with these read-only data structures. By mapping views in EF Core, you can query them as you would any other table or entity, while keeping your data access layer organized and efficient.</p><p>Whether you’re new to database views or looking to enhance your EF Core skills, this guide will equip you with the tools and knowledge to effectively integrate views into your data access strategy.</p><h3>Mapping a Database View in EF Core</h3><p>To map a view in EF Core, you typically treat it as an entity but with some important considerations since views are generally read-only.</p><h4>Step-by-Step Guide to Map a View</h4><h4><strong>1. Define the Entity Class</strong></h4><p>Create a class that represents the structure of the view. The class should include properties that match the columns in the view.</p><pre>public class SalesSummary<br>{<br>    public string ProductName { get; set; }<br>    public int TotalQuantitySold { get; set; }<br>    public decimal TotalSalesAmount { get; set; }<br>}</pre><h4><strong>2. Configure the Entity in </strong><strong>DbContext</strong></h4><p>Use the Fluent API in the OnModelCreating method to map the entity class to the view.</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;SalesSummary&gt; SalesSummaries { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        base.OnModelCreating(modelBuilder);<br><br>        // Map the SalesSummary entity to the view<br>        modelBuilder.Entity&lt;SalesSummary&gt;()<br>            .HasNoKey() // Views typically don&#39;t have keys<br>            .ToView(&quot;View_SalesSummary&quot;); // Specify the view name<br>    }<br>}</pre><ul><li><strong>HasNoKey()</strong>: Views in databases are inherently read-only structures, and they don’t usually have primary keys, which are required by EF Core for entities that are involved in data modification operations (insert, update, delete). Since views are not designed to handle these operations, we explicitly tell EF Core that this entity has no primary key by using the HasNoKey() method. Without this, EF Core would expect a primary key and throw an exception when querying the view.</li><li><strong>ToView(&quot;ViewName&quot;)</strong>: The ToView() method maps your entity class to the database view. The argument passed to this method is the <strong>exact name</strong> of the view as it exists in your database schema. EF Core will now understand that when you run a query against the SalesSummary entity, it should fetch data from the view named View_SalesSummary. Note that the name of the view must match exactly with how it’s defined in your database, including casing if your database is case-sensitive.</li></ul><h4>Why is This Important?</h4><p>This configuration ensures that EF Core treats the SalesSummary entity not as a typical table-backed entity, but as a <strong>read-only projection</strong> of data from the underlying view. Because views are typically used to simplify querying complex data (e.g., from joins or aggregations), mapping them correctly in EF Core allows your application to easily retrieve data from the view using LINQ or standard EF Core methods.</p><p>However, it’s crucial to remember that this entity is <strong>read-only</strong>: while you can query and retrieve data, you won’t be able to perform any operations that modify the data, such as inserts, updates, or deletions. Attempting to modify data through a view will result in a runtime exception unless the view itself is designed to be updatable (which is rare and dependent on the specific database engine you’re using).</p><h4><strong>3. Create the View in the Database</strong></h4><p>Ensure the view is created in the database. You can create it using a SQL script or include it as part of your migrations if desired.</p><pre>CREATE VIEW View_SalesSummary AS<br>SELECT<br>    ProductName,<br>    SUM(Quantity) AS TotalQuantitySold,<br>    SUM(Price * Quantity) AS TotalSalesAmount<br>FROM<br>    Orders<br>GROUP BY<br>    ProductName;</pre><h4><strong>4. Querying the View</strong></h4><p>You can query the view using LINQ as you would with any other <strong>DbSet</strong>.</p><pre>using (var context = new ApplicationDbContext())<br>{<br>    var salesData = context.SalesSummaries<br>        .Where(s =&gt; s.TotalSalesAmount &gt; 1000)<br>        .ToList();<br><br>    foreach (var item in salesData)<br>    {<br>        Console.WriteLine($&quot;{item.ProductName}: {item.TotalSalesAmount}&quot;);<br>    }<br>}</pre><h3>Important Considerations</h3><ol><li><strong>Read-Only Nature</strong>: Views are usually read-only. EF Core can query views, but it cannot update or insert into them. Attempting to modify data via a view will result in runtime exceptions unless the view is updatable, which is rare and depends on the database.</li><li><strong>No Primary Key</strong>: When mapping views, you typically use <strong>HasNoKey()</strong> because views don&#39;t have a primary key. <strong>EF Core requires a primary key to track changes for updates</strong>, which is unnecessary for views.</li><li><strong>Performance</strong>: Views can help optimize performance by encapsulating complex queries and reducing client-side logic. However, always analyze the execution plan to ensure the view is efficient.</li><li><strong>Complex Mapping</strong>: If your view is complex, ensure the entity class accurately reflects the view’s schema. Mismatches can lead to runtime errors.</li><li><strong>Migrations</strong>: If your view is part of your database schema, consider creating it in a migration. However, EF Core migrations primarily focus on tables, so views should be added using raw SQL in migrations.</li></ol><p><strong>Example Migration:</strong></p><pre>protected override void Up(MigrationBuilder migrationBuilder)<br>{<br>    migrationBuilder.Sql(@&quot;<br>        CREATE VIEW View_SalesSummary AS<br>        SELECT<br>            ProductName,<br>            SUM(Quantity) AS TotalQuantitySold,<br>            SUM(Price * Quantity) AS TotalSalesAmount<br>        FROM<br>            Orders<br>        GROUP BY<br>            ProductName;<br>    &quot;);<br>}<br><br>protected override void Down(MigrationBuilder migrationBuilder)<br>{<br>    migrationBuilder.Sql(&quot;DROP VIEW View_SalesSummary;&quot;);<br>}</pre><h3>Conclusion</h3><p>By following the steps outlined above, mapping a database view in EF Core becomes a straightforward process. Defining an entity class that reflects the view’s structure, configuring it with the Fluent API, and querying the data are all part of effectively integrating views into your application.</p><p>It’s important to remember that views are best suited for <strong>read-only access</strong>. Since they don’t have primary keys, they cannot support data modifications. This is where HasNoKey() comes in, signaling to EF Core that the entity will be used only for querying purposes. Mapping the entity to the view with ToView(&quot;ViewName&quot;) ensures that EF Core knows exactly where to fetch the data from, keeping your code clean and efficient.</p><p>Before querying, always ensure that the view is created in the database, whether through a SQL script or included as part of your migration. Once the view is properly mapped, you can query it just like any other entity in EF Core using LINQ, which provides the same flexibility and power for handling data retrieval without diving into raw SQL.</p><p>By understanding these nuances, you can harness the full potential of views to simplify your data access layer while keeping your application’s performance optimized.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c44dc8a0083" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Injection and How to Address]]></title>
            <link>https://medium.com/@yayasaafan/sql-injection-and-how-to-address-9a9f8e3738eb?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a9f8e3738eb</guid>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 10:55:43 GMT</pubDate>
            <atom:updated>2024-09-10T10:55:43.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPnUZBBDs-BQnnqt5_srQw.jpeg" /><figcaption>Generated By AI</figcaption></figure><h3>Introduction:</h3><p>SQL Injection is a serious security problem that happens when attackers can insert harmful code into an application’s database queries. This can let them access private data, change information, or even take control of the database. In this article, we’ll explain what SQL Injection is, how attackers use it, and share simple ways to protect your application from these attacks.</p><h3>What is SQL Injection?</h3><p>SQL Injection is a type of security vulnerability that occurs when an attacker is able to manipulate an application’s SQL queries by injecting malicious SQL code into input fields. This can allow the attacker to perform unauthorized actions on the database, such as retrieving sensitive data, modifying or deleting data, and even executing administrative operations on the database server.</p><h3>How SQL Injection Works?</h3><p>When user inputs are directly included in SQL queries without proper sanitization, attackers can craft inputs that manipulate the query structure. <strong>This can happen when dynamic SQL queries are constructed by concatenating strings</strong>, where user input is included without proper escaping or parameterization.</p><h3>Common SQL Injection Techniques</h3><h4><strong>1. Tautologies</strong></h4><p>Exploiting conditional statements in SQL queries to always return true, allowing attackers to bypass authentication or retrieve unauthorized data.</p><h4><strong>Example</strong>:</h4><p>Consider a login form where a user inputs a username and password:</p><pre>SELECT * <br>FROM Users <br>WHERE Username = &#39;user&#39; AND Password = &#39;pass&#39;;</pre><p><strong>An attacker</strong> can input &#39;&#39; OR &#39;1&#39;=&#39;1&#39; as the password, causing the query to be:</p><pre>SELECT * <br>FROM Users <br>WHERE Username = &#39;user&#39; AND Password = &#39;&#39; OR &#39;1&#39;=&#39;1&#39;;</pre><p>This query always returns true, potentially allowing the attacker to log in without valid credentials.</p><h4><strong>2. Union Attacks</strong></h4><p>Using the UNION operator to execute additional queries and retrieve data from other tables.</p><h4><strong>Example</strong>:</h4><p>An attacker might append a UNION query to extract data from another table:</p><pre>SELECT Name, Address FROM Customers WHERE CustomerId = 1<br>UNION<br>SELECT Username, Password FROM Users;</pre><p>This query attempts to retrieve user credentials by combining the results of two queries.</p><h4><strong>3. Blind SQL Injection</strong></h4><p>When an application is vulnerable to SQL injection but the results of the injection are not visible to the attacker, blind techniques are used. These rely on the response behavior to infer information.</p><h4><strong>Example</strong>:</h4><p>Using conditional logic in injected queries to determine database content based on server responses:</p><pre>SELECT Name FROM Products WHERE ProductId = 1 AND IF(1=1, sleep(10), null);</pre><p>If the server response is delayed, it indicates that the condition was true.</p><p><strong>Did you guess what the attacker’s next step could be?</strong></p><h4><strong>Example</strong>:</h4><p>An attacker inputs 1=1; DROP TABLE Users; -- into a form, attempting to delete the Users table:</p><pre>SELECT * FROM Products WHERE ProductId = 1=1; DROP TABLE Users; --;</pre><p>If errors are not properly handled, the attacker can infer database details and execute harmful commands.</p><h3>The Danger of String Concatenation and SQL Injection</h3><p>String concatenation involves directly building SQL queries by appending user inputs, which can be dangerous if not handled properly. This approach can lead to SQL injection attacks where malicious users can manipulate queries to execute arbitrary SQL commands.</p><h4>Example:</h4><pre>using (var context = new ApplicationDbContext())<br>{<br>    int customerId = 1;<br>    DateTime startDate = new DateTime(2024, 1, 1);<br><br>    // WARNING: Unsafe query due to direct concatenation of parameters<br>    var query = $&quot;SELECT * FROM GetCustomerOrdersByDate({customerId}, &#39;{startDate:yyyy-MM-dd}&#39;)&quot;;<br>    var orders = context.CustomerOrders.FromSqlRaw(query).ToList();<br><br>    foreach (var order in orders)<br>    {<br>        Console.WriteLine($&quot;Order {order.OrderId}: {order.TotalAmount}&quot;);<br>    }<br>}</pre><ul><li>If the parameters are user inputs, a malicious user could input SQL code that alters the query. For example, if customerId or startDate were directly from user input, they could insert additional SQL logic to manipulate the database.</li></ul><h3>Preventing SQL Injection</h3><h4><strong>1. Parameterized Queries</strong>:</h4><p>Use parameterized queries or prepared statements that separate SQL logic from data, ensuring inputs are treated strictly as data.</p><h4><strong>Example:</strong></h4><pre>using (var command = new SqlCommand(&quot;SELECT * FROM Users WHERE Username = @username AND Password = @password&quot;, connection))<br>{<br>    command.Parameters.AddWithValue(&quot;@username&quot;, username);<br>    command.Parameters.AddWithValue(&quot;@password&quot;, password);<br>    var reader = command.ExecuteReader();<br>}</pre><p>In this example, the query parameters @username and @password ensure that user inputs are treated as parameters, preventing SQL injection.</p><h4><strong>2. Stored Procedures</strong>:</h4><p>Use stored procedures with input parameters instead of dynamic SQL queries.</p><h4><strong>Example:</strong></h4><pre>CREATE PROCEDURE GetUserInfo @Username NVARCHAR(50), @Password NVARCHAR(50) <br>AS <br>BEGIN     <br>    SELECT * <br>    FROM Users <br>    WHERE Username = @Username AND Password = @Password; <br>END</pre><h4><strong>3. Input Validation</strong>:</h4><p>Validate and sanitize all user inputs to ensure they conform to expected patterns, data types, and do not contain malicious code.</p><h4><strong>4. Least Privilege</strong>:</h4><p>Grant the minimum necessary database permissions to the application to limit the potential impact of an injection attack.</p><h4><strong>5. Error Handling</strong>:</h4><p>Implement proper error handling to prevent detailed error messages from being displayed to users, which can give attackers insights into the database schema.</p><h4><strong>6. Security Tools</strong>:</h4><p>Use web application firewalls (WAFs) and security tools that can detect and block SQL injection attempts.</p><h4><strong>7. ORM Frameworks</strong>:</h4><p>Use Object-Relational Mapping (ORM) frameworks like Entity Framework, which handle parameterization automatically.</p><pre>var user = context.Users<br>    .Where(u =&gt; u.Username == username &amp;&amp; u.Password == password)<br>    .FirstOrDefault();</pre><h3>Conclusion:</h3><p>SQL Injection can put your application and data at risk, but by using safe coding practices like parameterized queries and input validation, you can prevent these attacks. Keeping security in mind while developing your applications helps protect your users and keeps your data safe. By taking these steps, you make sure your application is better protected from harmful attacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a9f8e3738eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering EF Core Configuration: Part 4 — Exclusion and Inclusion of Entities]]></title>
            <link>https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-4-exclusion-and-inclusion-of-entities-1d1f7daa5fe9?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d1f7daa5fe9</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-relational-mapping]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 11:46:41 GMT</pubDate>
            <atom:updated>2024-09-09T11:46:41.880Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering EF Core Configuration: Part 4 — Exclusion and Inclusion of Entities</h3><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nq7xDl4vmA_qK_Q76vFsSg.png" /></figure><p>In the last story, we delved into the Fluent API in EF Core “<a href="https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-3-exploring-fluent-api-7278cff01271">Mastering EF Core Configuration: Part 3 — Exploring Fluent API</a>” and explored how it provides greater flexibility and control over configuring your data models. From overriding default conventions to configuring relationships, table mappings, and even handling concurrency, the Fluent API empowers developers to fine-tune every aspect of their database schema.</p><p>Today, we’ll shift our focus to the next important topic: <strong>Exclusion and Inclusion of Entities in EF Core</strong>. We’ll explore how EF Core allows you to include or exclude specific entities during query execution, ensuring optimized performance and precise control over the data you retrieve. Let’s dive in!</p><h3>Exclusion and Inclusion of Entities</h3><p>You can exclude entire entities or specific properties from being mapped to your database schema using both the Fluent API and Data Annotations. Each approach provides different levels of control and can be used depending on your specific requirements. Here’s a detailed explanation of how to use both methods.</p><h3>Excluding Entities</h3><h4>Using Fluent API</h4><p>The Fluent API provides a straightforward way to exclude entire entities from being mapped to the database.</p><p>To exclude an entity class from being mapped to a table, use the <strong>Ignore&lt;TEntity&gt;()</strong> method in the OnModelCreating method of your DbContext.</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br>    public DbSet&lt;Order&gt; Orders { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        base.OnModelCreating(modelBuilder);<br><br>        //Exclude AuditLog from being mapped to the database<br>        modelBuilder.Ignore&lt;AuditLog&gt;();<br>    }<br>}<br><br>public class AuditLog<br>{<br>    public int AuditLogId { get; set; }<br>    public string Action { get; set; }<br>    public DateTime Timestamp { get; set; }<br>}</pre><p>In this example, the AuditLog class will not be mapped to a database table, effectively excluding it from the model.</p><h4>Using Data Annotations</h4><p>When you apply the <strong>[NotMapped]</strong> attribute to a class, EF Core will not map the class to a database table, effectively excluding it from the database schema.</p><h4>Example:</h4><p>Suppose you have a class <strong>AuditLog </strong>that you do not want to be mapped to the database:</p><pre>using System.ComponentModel.DataAnnotations.Schema;<br><br>[NotMapped]<br>public class AuditLog<br>{<br>    public int AuditLogId { get; set; }<br>    public string Action { get; set; }<br>    public DateTime Timestamp { get; set; }<br>}</pre><p>In this example, the AuditLog class is decorated with the [NotMapped] attribute, ensuring that EF Core does not create a table for this class in the database.</p><h4>When to Use [NotMapped] on a Class?</h4><ul><li><strong>DTOs and View Models</strong>: If you are using a class purely for data transfer or presentation purposes and do not want it to be part of the database schema.</li><li><strong>Helper Classes</strong>: Classes that provide utility functions or aggregate data that do not need to be persisted.</li><li><strong>Temporary Data</strong>: Classes used for temporary data processing or caching within your application.</li></ul><h3>Excluding Properties</h3><h4>Using Fluent API</h4><p>You can exclude specific properties of an entity from being mapped to the database using the <strong>Ignore </strong>method on the EntityTypeBuilder.</p><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br>    public DateTime DateOfBirth { get; set; }<br><br>    // This property will not be mapped to the database<br>    public string TemporaryData { get; set; }<br>}<br><br>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    base.OnModelCreating(modelBuilder);<br><br>    // Exclude TemporaryData from being mapped to the database<br>    modelBuilder.Entity&lt;Customer&gt;()<br>        .Ignore(c =&gt; c.TemporaryData);<br>}</pre><p>Here, the <strong>TemporaryData </strong>property of the <strong>Customer </strong>class is ignored, and it will not appear in the database schema.</p><h4>Using Data Annotations</h4><p>Data Annotations can be used to exclude specific properties by marking them with <strong>[NotMapped]</strong>.</p><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br>    public DateTime DateOfBirth { get; set; }<br><br>    [NotMapped]<br>    public string TemporaryData { get; set; } // Not mapped to the database<br>}</pre><p>The [NotMapped] attribute tells EF Core to exclude the TemporaryData property from the database schema.</p><h3>Conditional Exclusion</h3><p>Sometimes, you might want to conditionally exclude entities or properties based on configuration settings or runtime conditions.</p><h4><strong>Example:</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    base.OnModelCreating(modelBuilder);<br><br>    bool includeAudit = false; //Determine this from configuration<br><br>    if (!includeAudit)<br>    {<br>        modelBuilder.Ignore&lt;AuditLog&gt;(); **//Conditionally ignore entity**<br>    }<br>}</pre><h3>Scenarios Where EF Core Considers a Class as an Entity (Including Entities)</h3><h4>1. Defined as a DbSet in DbContext</h4><p>When a class is defined as a DbSet&lt;TEntity&gt; in the DbContext, EF Core automatically treats it as an entity and includes it in migrations and database operations.</p><h4><strong>Example:</strong></h4><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br>    public DbSet&lt;Order&gt; Orders { get; set; }<br>}</pre><p>In this example, Customer and Order are entities because they are defined as DbSet properties in the DbContext.</p><h4>2. Included in the Model via Fluent API</h4><p>Even if a class is not defined as a DbSet, you can explicitly include it as an entity using the Fluent API in the OnModelCreating method.</p><h4><strong>Example:</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    base.OnModelCreating(modelBuilder);<br><br>    //Explicitly include Product as an entity<br>    modelBuilder.Entity&lt;Product&gt;();<br>}</pre><p>In this case, Product is considered an entity because it is explicitly added to the model configuration.</p><h4>3. Defined in a Relationship</h4><p>If a class is referenced in a relationship with another entity (e.g., through navigation properties), EF Core may automatically consider it an entity, even if it’s not explicitly defined as a DbSet.</p><p><strong>Example:</strong></p><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br>    public ICollection&lt;Order&gt; Orders { get; set; }<br>}<br><br>public class Order<br>{<br>    public int OrderId { get; set; }<br>    public int CustomerId { get; set; }<br>    public Customer Customer { get; set; }<br>}</pre><p>Here, Order is considered an entity because it is part of the Customer entity&#39;s relationships.</p><h3>Considerations and Best Practices</h3><ul><li><strong>Explicit Definition</strong>: Whenever possible, define your entities explicitly using <strong>DbSet</strong> or Fluent API for clarity and maintainability.</li><li><strong>Avoid Ambiguity</strong>: Ensure that entities are clearly defined to avoid accidental exclusions or inclusions that might lead to unexpected behavior in migrations.</li><li><strong>Review Migrations</strong>: Regularly review generated migrations to ensure that all intended entities and relationships are correctly captured.</li><li><strong>Testing</strong>: Test schema changes in a development or staging environment before applying them to production to catch any issues early.</li></ul><h3>Key Points about Entity Access without DbSet</h3><ul><li><strong>Database Table Creation</strong>: EF Core will create a table for any entity defined using the Fluent API or included through relationships, even if it is not explicitly defined as a DbSet in the DbContext.</li><li><strong>Lack of Direct Access</strong>: Without a DbSet property, you cannot directly perform LINQ queries or CRUD operations on the entity using the DbContext instance. This means you can&#39;t directly use methods like context.Entities.Add() or context.Entities.Where().</li></ul><h4><strong>Accessing Entities Without </strong><strong>DbSet</strong>:</h4><p>You can use the <strong>Set&lt;TEntity&gt;()</strong> method of DbContext to access entities not defined as DbSet. This method provides a generic DbSet that can be used for querying and updates.</p><pre>using (var context = new ApplicationDbContext())<br>{<br>    //Access Product entity using Set&lt;Product&gt;()<br>    var products = context.Set&lt;Product&gt;().ToList();<br><br>    //Perform CRUD operations<br>    context.Set&lt;Product&gt;().Add(new Product { Name = &quot;New Product&quot;, Price = 10.99m });<br>    context.SaveChanges();<br>}</pre><h3>Conclusion</h3><p>The ability to strategically include or exclude entities and properties in EF Core allows you to craft a more efficient and tailored database schema. Whether you’re optimizing for performance, simplifying data models, or managing dynamic application requirements, both the Fluent API and Data Annotations provide powerful tools to control your entity mappings. By thoughtfully applying these techniques, you can reduce unnecessary complexity, enhance the clarity of your data structure, and ensure your application runs smoothly with only the necessary data in play.</p><p>As you move forward, consistently reviewing your entity configurations and leveraging these exclusion strategies will enable you to build more maintainable and scalable systems that can easily adapt to evolving business needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d1f7daa5fe9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering EF Core Configuration: Part 3 — Exploring Fluent API]]></title>
            <link>https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-3-exploring-fluent-api-7278cff01271?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/7278cff01271</guid>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 11:27:32 GMT</pubDate>
            <atom:updated>2024-09-02T11:27:32.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering EF Core Configuration: Part 3 — Exploring Fluent API</h3><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nq7xDl4vmA_qK_Q76vFsSg.png" /></figure><p>In our previous journey through EF Core configurations, we explored the power of Data Annotations. “<a href="https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-2-exploring-data-annotations-24dbcab6e0f0">Mastering EF Core Configuration: Part 2 — Exploring Data Annotations</a>” These attributes allowed us to easily define primary keys, relationships, validation rules, and even manage concurrency, all within our entity classes. While Data Annotations offer a convenient way to configure your models with minimal effort, they have their limitations, especially when it comes to more complex scenarios that require greater flexibility and precision.</p><p>Now, it’s time to dive deeper into the world of EF Core configurations by exploring the <strong>Fluent API</strong>. The Fluent API provides a more powerful and flexible approach to configuring your models, allowing you to fine-tune every aspect of your database schema and behavior. In this first part of our Fluent API exploration, we’ll cover the basics and start to unlock the full potential of EF Core, giving you the tools to take your data models to the next level.</p><h3>Key Features of the Fluent API</h3><ul><li><strong>Greater Flexibility</strong>: Offers more configuration options compared to Data Annotations.</li><li><strong>Override Conventions</strong>: Allows you to override EF Core’s default conventions for model configuration.</li><li><strong>Configure Relationships</strong>: Provides detailed configuration options for relationships between entities.</li><li><strong>Control Table and Column Mapping</strong>: Customize table and column names, data types, and more.</li></ul><h3>Where Should We Write Our Configurations?</h3><p>When working with Entity Framework Core, deciding where to write your configurations can have a significant impact on the organization and scalability of your application. Configurations can be placed directly inside the OnModelCreating method of your DbContext, separated into individual classes using the IEntityTypeConfiguration&lt;T&gt; interface, or automatically applied from an assembly. Each method offers its own advantages, depending on the size and complexity of your project. To explore these options in detail and find out which approach best suits your needs, check out the article <strong>&quot;</strong><a href="https://medium.com/@yayasaafan/organizing-ef-core-configurations-from-direct-setup-to-scalable-solutions-e3c2c47c1ac4"><strong>Organizing EF Core Configurations: From Direct Setup to Scalable Solutions</strong></a><strong>&quot;</strong></p><h3>Configuring with the Fluent API</h3><p>Here are some of the key configurations you can perform using the Fluent API:</p><h4>1. Configuring Entity Properties</h4><p>You can configure properties for entities, including setting primary keys, data types, and constraints.</p><h4><strong>Primary Key Configuration</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;Product&#39; entity<br>    modelBuilder.Entity&lt;Product&gt;()<br>        <br>        // Sets the &#39;ProductId&#39; property as the primary key for the &#39;Product&#39; entity<br>        .HasKey(p =&gt; p.ProductId);<br>}</pre><ul><li>The Entity&lt;T&gt; method is used to select the entity type you want to configure.</li><li>The HasKey method is used to specify which property (or properties, in the case of composite keys) should act as the primary key for the entity.</li></ul><p><strong>Example of how to configure a composite key:</strong></p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;OrderDetail&#39; entity<br>    modelBuilder.Entity&lt;OrderDetail&gt;()<br>        <br>        // Configures a composite key using &#39;OrderId&#39; and &#39;ProductId&#39;<br>        .HasKey(od =&gt; new { od.OrderId, od.ProductId });<br>}</pre><p><strong>Note that:</strong></p><ul><li>A composite key is a primary key that consists of more than one property, meaning both OrderId and ProductId together must be unique in the OrderDetail table to uniquely identify each record.</li></ul><h4><strong>Column Mapping</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;Product&#39; entity<br>    modelBuilder.Entity&lt;Product&gt;()<br>        <br>        // Accesses the &#39;Name&#39; property of the &#39;Product&#39; entity for configuration<br>        .Property(p =&gt; p.Name)<br>        <br>        // Maps the &#39;Name&#39; property to a column named &quot;ProductName&quot; in the database<br>        .HasColumnName(&quot;ProductName&quot;)<br>        <br>        // Specifies that the SQL data type for the &#39;ProductName&#39; column should be &quot;nvarchar(100)&quot;<br>        .HasColumnType(&quot;nvarchar(100)&quot;);<br>}</pre><p><strong>Note that:</strong></p><ul><li>The Entity&lt;T&gt; method is used to select the entity type you want to configure.</li><li>The Property method allows you to specify configurations at the property level.</li><li>The HasColumnName method is used to map a property to a specific column name in the database.</li><li>The HasColumnType method allows you to specify the exact SQL data type that should be used for the column in the database.</li></ul><h4><strong>Required and MaxLength</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;Product&#39; entity<br>    modelBuilder.Entity&lt;Product&gt;()<br>        <br>        // Accesses the &#39;Name&#39; property of the &#39;Product&#39; entity for configuration<br>        .Property(p =&gt; p.Name)<br>        <br>        // Marks the &#39;Name&#39; property as required, meaning it cannot be null<br>        .IsRequired()<br>        <br>        // Sets the maximum length of the &#39;Name&#39; property to 100 characters<br>        .HasMaxLength(100);<br>}</pre><ul><li>The Entity&lt;T&gt; method is used to specify which entity type you&#39;re working with.</li><li>The Property method allows you to specify configurations at the property level.</li><li>The IsRequired method adds a NOT NULL constraint to the corresponding column in the database.</li><li>The HasMaxLength method modifies the schema to limit the number of characters allowed in the column in the database.</li></ul><h4>2. Configuring Relationships</h4><p>The Fluent API allows you to define relationships between entities, including one-to-one, one-to-many, and many-to-many.</p><h4><strong>One-to-Many Relationship</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configure the &#39;Order&#39; entity<br>    modelBuilder.Entity&lt;Order&gt;()<br>        <br>        // Specifies that each &#39;Order&#39; has one related &#39;Customer&#39; entity<br>        .HasOne(o =&gt; o.Customer)<br>        <br>        // Configures the relationship to indicate that a &#39;Customer&#39; can have many &#39;Orders&#39;<br>        .WithMany(c =&gt; c.Orders)<br>        <br>        // Sets the foreign key property in the &#39;Order&#39; entity that references the &#39;Customer&#39; entity<br>        .HasForeignKey(o =&gt; o.CustomerId);<br>}</pre><ul><li>The Entity&lt;T&gt; method is used to specify which entity type you&#39;re working with.</li><li>The HasOne method is used for configuring one-to-one or one-to-many relationships where this entity (Order) has one related entity.</li><li>The WithMany method specifies the collection of related entities (Orders) in the Customer entity, defining a one-to-many relationship.</li><li>The HasForeignKey method is used to define which property in the Order entity serves as the foreign key in this relationship.</li></ul><h4><strong>One-to-One Relationship</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;User&#39; entity<br>    modelBuilder.Entity&lt;User&gt;()<br>        <br>        // Specifies that the &#39;User&#39; entity has one related &#39;Profile&#39; entity<br>        .HasOne(u =&gt; u.Profile)<br>        <br>        // Configures the relationship to indicate that the &#39;Profile&#39; entity <br>        // is related to one &#39;User&#39; entity (one-to-one relationship)<br>        .WithOne(p =&gt; p.User)<br>        <br>        // Sets the foreign key in the &#39;Profile&#39; entity that references the &#39;User&#39; entity<br>        .HasForeignKey&lt;Profile&gt;(p =&gt; p.UserId);<br>}</pre><ul><li>The Entity&lt;T&gt; method is used to select the entity type you want to configure.</li><li>The HasOne method is used to configure one-to-one or one-to-many relationships where this entity (User) has one related entity.</li><li>The WithOne method is used to define the one-to-one relationship between the User and Profile entities.</li><li>The HasForeignKey method is used to define which property in the dependent entity (Profile) serves as the foreign key in this relationship.</li></ul><h4><strong>Many-to-Many Relationship</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;Course&#39; entity<br>    modelBuilder.Entity&lt;Course&gt;()<br>        <br>        // Specifies that the &#39;Course&#39; entity has a collection of related &#39;Student&#39; entities<br>        .HasMany(c =&gt; c.Students)<br>        <br>        // Configures the relationship to indicate that the &#39;Student&#39; entity <br>        // has a collection of related &#39;Course&#39; entities (many-to-many relationship)<br>        .WithMany(s =&gt; s.Courses)<br>        <br>        // Specifies the join entity &#39;Enrollment&#39; that maps the many-to-many relationship<br>        .UsingEntity&lt;Enrollment&gt;(<br>            <br>            // Configures the relationship between &#39;Enrollment&#39; and &#39;Student&#39;<br>            j =&gt; j.HasOne(e =&gt; e.Student)<br>                  .WithMany(s =&gt; s.Enrollments),<br>            <br>            // Configures the relationship between &#39;Enrollment&#39; and &#39;Course&#39;<br>            j =&gt; j.HasOne(e =&gt; e.Course)<br>                  .WithMany(c =&gt; c.Enrollments));<br>}</pre><ul><li>The Entity&lt;T&gt; method is used to select the entity type you want to configure.</li><li>The HasMany method is used to configure one-to-many or many-to-many relationships where this entity (Course) has many related entities.</li><li>The WithMany method is used to define the many-to-many relationship between the Course and Student entities.</li><li>The UsingEntity method is used to define how the relationship is mapped using a join table.</li><li><strong>j =&gt; j.HasOne(e =&gt; e.Student).WithMany(s =&gt; s.Enrollments)</strong>: This part configures the relationship between the Enrollment join entity and the Student entity. It specifies that each Enrollment is related to one Student, and each Student can have many Enrollments.</li><li><strong>j =&gt; j.HasOne(e =&gt; e.Course).WithMany(c =&gt; c.Enrollments)</strong>: This part configures the relationship between the Enrollment join entity and the Course entity. It specifies that each Enrollment is related to one Course, and each Course can have many Enrollments.</li></ul><h4>3. Configuring Concurrency</h4><p>You can configure concurrency tokens using the Fluent API to achieve the same behavior as <strong>[Timestamp]</strong> and <strong>[ConcurrencyCheck]</strong>.</p><h4><strong>Timestamp (Row Version)</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;Product&#39; entity<br>    modelBuilder.Entity&lt;Product&gt;()<br>        <br>        // Accesses the &#39;RowVersion&#39; property of the &#39;Product&#39; entity for configuration<br>        .Property(p =&gt; p.RowVersion)<br>        <br>        // Configures the &#39;RowVersion&#39; property as a concurrency token (also known as a timestamp)<br>        .IsRowVersion(); <br>}</pre><ul><li>The Entity&lt;T&gt; method is used to select the entity type you want to configure.</li><li>The Property method allows you to configure specific properties within the entity.</li><li>The IsRowVersion method marks the property as a special database field that will be automatically updated by the database each time a record is updated. This property is typically used for optimistic concurrency control, ensuring that no two processes can update the same record simultaneously without detecting the conflict.</li></ul><h4><strong>ConcurrencyCheck for Specific Properties</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;Product&#39; entity<br>    modelBuilder.Entity&lt;Product&gt;()<br>        <br>        // Accesses the &#39;Price&#39; property of the &#39;Product&#39; entity for configuration<br>        .Property(p =&gt; p.Price)<br>        <br>        // Configures the &#39;Price&#39; property as a concurrency token<br>        .IsConcurrencyToken();<br>}</pre><ul><li>The Entity&lt;T&gt; method is used to select the entity type you want to configure.</li><li>The Property method allows you to specify configurations for individual properties within the entity.</li><li>The IsConcurrencyToken method marks the Price property so that EF Core will include it in the WHERE clause of update and delete statements to check for concurrency conflicts. This ensures that the property hasn&#39;t been modified by another transaction since it was loaded, helping to prevent conflicting changes.</li></ul><h4>4. Configuring Table and Schema</h4><p>You can specify table and schema names for entities.</p><h4><strong>Table and Schema Mapping</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;Product&#39; entity<br>    modelBuilder.Entity&lt;Product&gt;()<br>        <br>        // Maps the &#39;Product&#39; entity to a table named &quot;ProductsTable&quot; within the &quot;Inventory&quot; schema in the database<br>        .ToTable(&quot;ProductsTable&quot;, schema: &quot;Inventory&quot;);<br>}</pre><ul><li>The Entity&lt;T&gt; method is used to select the entity type you want to configure.</li><li>The ToTable method is used to customize the table name and schema where the entity&#39;s data will be stored. By default, EF Core uses the entity class name as the table name, but this method allows you to override that default behavior.</li></ul><h4>5. Indexes</h4><p>You can configure indexes on columns using the Fluent API.</p><h4><strong>Index Configuration</strong></h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configures the &#39;Product&#39; entity<br>    modelBuilder.Entity&lt;Product&gt;()<br>        <br>        // Creates an index on the &#39;Name&#39; property of the &#39;Product&#39; entity<br>        .HasIndex(p =&gt; p.Name)<br>        <br>        // Specifies a custom name for the index in the database as &quot;IX_Product_Name&quot;<br>        .HasDatabaseName(&quot;IX_Product_Name&quot;);<br>}</pre><ul><li>The Entity&lt;T&gt; method is used to select the entity type you want to configure.</li><li>The HasIndex method allows you to specify one or more properties that should be indexed in the database.</li><li>By default, EF Core generates index names, but the HasDatabaseName method allows you to specify a custom name that may align with your database naming conventions or make the index easier to identify.</li></ul><h3>Using Fluent API to Implement InverseProperty Logic</h3><p>Let’s consider a scenario similar to the one we’ve discussed previously, where you have an <strong>Employee </strong>entity that can manage projects and also work on them. Here&#39;s how you can configure this relationship using the Fluent API.</p><h3>Example Scenario</h3><p>Suppose you have the following entity classes:</p><pre>public class Employee<br>{<br>    public int EmployeeId { get; set; }<br><br>    public string Name { get; set; }<br><br>    public ICollection&lt;Project&gt; ManagedProjects { get; set; }<br><br>    public ICollection&lt;Project&gt; DevelopedProjects { get; set; }<br>}<br><br>public class Project<br>{<br>    public int ProjectId { get; set; }<br><br>    public string Title { get; set; }<br><br>    public int ManagerId { get; set; }<br><br>    public Employee Manager { get; set; }<br><br>    public int DeveloperId { get; set; }<br><br>    public Employee Developer { get; set; }<br>}</pre><h3>Configuring Relationships with Fluent API</h3><p>To replicate the logic of <strong>[InverseProperty]</strong>, use the Fluent API to define the relationships explicitly:</p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Configuring the one-to-many relationship for ManagedProjects<br>    modelBuilder.Entity&lt;Project&gt;()<br>        <br>        // Specifies that each Project has one Manager (Employee)<br>        .HasOne(p =&gt; p.Manager)<br>        <br>        // Specifies that an Employee can manage many Projects<br>        .WithMany(e =&gt; e.ManagedProjects)<br>        <br>        // Defines the foreign key in the Project entity that references the Manager (Employee)<br>        .HasForeignKey(p =&gt; p.ManagerId)<br>        <br>        // Sets the delete behavior to Restrict, meaning the Manager cannot be deleted if there are related Projects<br>        .OnDelete(DeleteBehavior.Restrict);<br><br>    // Configuring the one-to-many relationship for DevelopedProjects<br>    modelBuilder.Entity&lt;Project&gt;()<br>        <br>        // Specifies that each Project has one Developer (Employee)<br>        .HasOne(p =&gt; p.Developer)<br>        <br>        // Specifies that an Employee can work as a developer on many Projects<br>        .WithMany(e =&gt; e.DevelopedProjects)<br>        <br>        // Defines the foreign key in the Project entity that references the Developer (Employee)<br>        .HasForeignKey(p =&gt; p.DeveloperId)<br>        <br>        // Sets the delete behavior to Restrict, meaning the Developer cannot be deleted if there are related Projects<br>        .OnDelete(DeleteBehavior.Restrict);<br>}</pre><h3>Explanation</h3><ul><li><strong>HasOne</strong>: Specifies that the <strong>Project </strong>entity has a single <strong>Manager </strong>or <strong>Developer</strong>.</li><li><strong>WithMany</strong>: Indicates that the <strong>Employee </strong>entity can have multiple <strong>ManagedProjects </strong>or <strong>DevelopedProjects</strong>.</li><li><strong>HasForeignKey</strong>: Defines the foreign key property in the <strong>Project </strong>entity (<strong>ManagerId </strong>or <strong>DeveloperId</strong>) that references the <strong>Employee </strong>entity.</li><li><strong>OnDelete</strong>: Configures the delete behavior (optional). In this case, <strong>DeleteBehavior</strong>.<strong>Restrict </strong>prevents deletion of an <strong>Employee </strong>if they are referenced as a manager or developer in any <strong>Project</strong>.</li></ul><h3>Delete Behaviors in EF Core</h3><p>EF Core supports several delete behaviors:</p><ul><li><strong>Cascade</strong>: Deletes the dependent entities when the principal is deleted. Used by default for required relationships.</li><li><strong>SetNull</strong>: Sets the foreign key to null when the principal is deleted. Suitable for optional relationships.</li><li><strong>Restrict</strong>: Prevents the principal entity from being deleted if there are related dependents.</li><li><strong>NoAction</strong>: No action is taken by EF Core on delete, leaving it to the database to enforce constraints.</li></ul><h3>When to Use the Fluent API</h3><ul><li><strong>Complex Configurations</strong>: When you need more control than what Data Annotations can provide.</li><li><strong>Override Conventions</strong>: When you want to override EF Core’s default conventions for naming or relationships.</li><li><strong>Centralized Configuration</strong>: Keeping all configurations in one place (in <strong>OnModelCreating</strong>) can make it easier to manage and understand complex models.</li></ul><h3>Conclusion</h3><p>In this article, we’ve explored various aspects of configuring relationships and properties in EF Core using the Fluent API. From setting up primary keys, including composite keys, to configuring one-to-many relationships and handling concurrency with tokens, the Fluent API provides powerful tools to fine-tune your data models. We also looked at how to map entities to specific tables and schemas, create custom indexes, and manage delete behaviors to maintain data integrity.</p><p>The Fluent API’s flexibility allows you to achieve configurations that go beyond the limitations of Data Annotations, giving you full control over how your entities interact with the database. As you continue to build more complex applications, mastering these configurations will enable you to create efficient, maintainable, and scalable data models.</p><p>In the next part of our series, we’ll dive even deeper into more advanced configurations, where the Fluent API will play a crucial role in shaping your data models. We’ll explore topics such as table splitting, inheritance mapping, and more. Stay tuned as we continue to unlock the full potential of EF Core!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7278cff01271" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Organizing EF Core Configurations: From Direct Setup to Scalable Solutions]]></title>
            <link>https://medium.com/@yayasaafan/organizing-ef-core-configurations-from-direct-setup-to-scalable-solutions-e3c2c47c1ac4?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c2c47c1ac4</guid>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[configuration]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 10:50:41 GMT</pubDate>
            <atom:updated>2024-09-02T10:50:41.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nq7xDl4vmA_qK_Q76vFsSg.png" /></figure><p>When building applications with Entity Framework Core (EF Core), how you structure your model configurations can greatly influence the maintainability and scalability of your project. EF Core offers several ways to configure your data models within the OnModelCreating method of the DbContext, each catering to different project needs. Whether you&#39;re working on a small, straightforward application or a large, complex system, choosing the right configuration method is key to keeping your code organized and efficient. In this article, we’ll explore three main approaches to configuring your EF Core models: Direct Configuration, using the IEntityTypeConfiguration&lt;T&gt; interface, and Applying Configurations from Assembly. Each method has its own strengths, and understanding when to use them will help you create a well-structured and scalable application.</p><h3>1. Direct Configuration Inside OnModelCreating</h3><p>The simplest way to configure your model is to define the configurations directly within the OnModelCreating method. This is suitable for smaller applications where the number of entities and configurations is manageable.</p><h4>Example:</h4><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    base.OnModelCreating(modelBuilder);<br><br>    // Configure Product entity<br>    modelBuilder.Entity&lt;Product&gt;(entity =&gt;<br>    {<br>        entity.HasKey(p =&gt; p.ProductId);<br>        entity.Property(p =&gt; p.Name)<br>            .IsRequired()<br>            .HasMaxLength(100);<br>        entity.Property(p =&gt; p.Price)<br>            .IsConcurrencyToken();<br>    });<br><br>    // Configure Order entity and its relationship with Customer<br>    modelBuilder.Entity&lt;Order&gt;(entity =&gt;<br>    {<br>        entity.HasKey(o =&gt; o.OrderId);<br>        entity.HasOne(o =&gt; o.Customer)<br>            .WithMany(c =&gt; c.Orders)<br>            .HasForeignKey(o =&gt; o.CustomerId);<br>    });<br>}</pre><h3>2. Using the IEntityTypeConfiguration&lt;T&gt; Interface</h3><p>As your application grows, managing the configurations for all your entities directly within the OnModelCreating method can become cumbersome and difficult to maintain. This is where the IEntityTypeConfiguration&lt;T&gt; interface comes in handy. By implementing this interface, you can separate the configurations for each entity into individual classes, leading to better organization and easier maintenance.</p><h4>What Does the IEntityTypeConfiguration&lt;T&gt; Interface Provide?</h4><p>The IEntityTypeConfiguration&lt;T&gt; interface allows you to define the configuration logic for an entity in a separate class, rather than cluttering your DbContext class with configuration details. This separation of concerns not only makes your code more organized but also more modular. Each entity’s configuration is encapsulated within its own class, making it easier to locate, modify, and extend as needed.</p><h4>How to Use the IEntityTypeConfiguration&lt;T&gt; Interface?</h4><p>To use this interface, follow these steps:</p><p><strong>1- Define Configuration Classes:</strong></p><ul><li>Create a class for each entity you want to configure.</li><li>Implement the IEntityTypeConfiguration&lt;T&gt; interface in these classes.</li><li>Inside the Configure method of the interface, define all the necessary configurations for the entity.</li></ul><p><strong>Example:</strong></p><pre>public class ProductConfiguration : IEntityTypeConfiguration&lt;Product&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Product&gt; builder)<br>    {<br>        builder.HasKey(p =&gt; p.ProductId);<br>      <br>        builder.Property(p =&gt; p.Name)<br>          .IsRequired()<br>          .HasMaxLength(100);<br>       <br>        builder.Property(p =&gt; p.Price)<br>        .IsConcurrencyToken();<br>    }<br>}<br><br>public class OrderConfiguration : IEntityTypeConfiguration&lt;Order&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Order&gt; builder)<br>    {<br>        builder.HasKey(o =&gt; o.OrderId);<br><br>        builder.HasOne(o =&gt; o.Customer)<br>          .WithMany(c =&gt; c.Orders)<br>          .HasForeignKey(o =&gt; o.CustomerId);<br>    }<br>}</pre><p><strong>2- Register Configurations in </strong><strong>OnModelCreating:</strong></p><ul><li>After defining your configuration classes, you need to register them in the OnModelCreating method of your DbContext.</li><li>Use the ApplyConfiguration method to apply each configuration class to its corresponding entity.</li></ul><p><strong>Example:</strong></p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    base.OnModelCreating(modelBuilder);<br><br>    modelBuilder.ApplyConfiguration(new ProductConfiguration());<br>    modelBuilder.ApplyConfiguration(new OrderConfiguration());<br>}</pre><h4>Where and How to Organize These Configuration Classes?</h4><p>It’s a good practice to keep these configuration classes in a dedicated folder or namespace within your project. You might name this folder <strong>Configurations </strong>or <strong>EntityConfigurations</strong>, depending on your project structure. This organization makes it easy to manage and locate all configuration files.</p><h4><strong>Advantages:</strong></h4><ul><li><strong>Separation of Concerns:</strong> Each configuration class focuses only on one entity, making it easier to manage.</li><li><strong>Reusability:</strong> If your application is modular, these configurations can be reused across different parts of your project.</li><li><strong>Maintainability:</strong> As your application evolves, making changes to an entity’s configuration is straightforward because all the configuration logic is in one place.</li></ul><h3>3. Applying Configurations from Assembly</h3><p>This approach automatically applies all configurations from a specified assembly. It is useful for large-scale applications where configurations are spread across multiple classes.</p><h4>Example:</h4><p><strong>Define Configuration Classes</strong> (same as in the previous example)</p><p><strong>Apply Configurations in </strong><strong>OnModelCreating</strong></p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    // Always call the base method to ensure any configurations from the base class are applied.<br>    base.OnModelCreating(modelBuilder);<br><br>    // Automatically apply all configurations defined in the current assembly.<br>    // This is particularly useful for large applications, as it eliminates the need to<br>    // manually register each configuration class in the &#39;OnModelCreating&#39; method.<br>    modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly);<br>}</pre><ul><li><strong>ApplyConfigurationsFromAssembly</strong>: This method scans the specified assembly for any classes that implement the IEntityTypeConfiguration&lt;T&gt; interface and automatically applies their configurations to the corresponding entities.</li><li><strong>typeof(ApplicationDbContext).Assembly</strong>: This specifies the assembly to scan. By passing typeof(ApplicationDbContext).Assembly, EF Core will look in the same assembly where ApplicationDbContext is defined, ensuring that all configuration classes in that assembly are automatically applied.</li></ul><h3>Why Call the Base Method First?</h3><ol><li><strong>Future Compatibility</strong>: While the default DbContext implementation doesn&#39;t perform operations in OnModelCreating, calling base.OnModelCreating(modelBuilder) ensures that if future versions of EF Core add logic to this method, your configurations won&#39;t interfere with it.</li><li><strong>Standard Practice</strong>: It is a good practice in object-oriented programming to call the base class’s method when overriding methods unless you have a specific reason not to. This maintains consistency and clarity in your code.</li><li><strong>Framework Extensions</strong>: If you are using extensions or libraries that might alter or extend the DbContext, calling the base method first allows those extensions to apply their configurations before you apply yours.</li></ol><h3>Advantages of Each Approach</h3><h4>1- Direct Configuration</h4><ul><li><strong>Simplicity</strong>: Easy to implement for small projects.</li><li><strong>Quick Setup</strong>: No additional classes needed.</li></ul><h4>2- IEntityTypeConfiguration&lt;T&gt; Interface</h4><ul><li><strong>Separation of Concerns</strong>: Keeps configuration logic separate from DbContext.</li><li><strong>Reusability</strong>: Configurations can be reused and tested independently.</li><li><strong>Maintainability</strong>: Easier to manage in larger projects with many entities.</li></ul><h4>3- Applying Configurations from Assembly</h4><ul><li><strong>Automation</strong>: Automatically applies all configuration classes, reducing boilerplate.</li><li><strong>Scalability</strong>: Ideal for large projects with many configuration classes.</li><li><strong>Flexibility</strong>: Easy to add new configurations without modifying the DbContext.</li></ul><h3>Conclusion</h3><p>Choosing the right approach to configure your EF Core models is essential for building a maintainable and scalable application. For smaller projects, Direct Configuration inside OnModelCreating is a quick and straightforward method.</p><p>As your application grows, adopting the IEntityTypeConfiguration&lt;T&gt; interface provides better organization and separation of concerns, making your configurations easier to manage and extend.</p><p>For large-scale projects, automating the application of configurations from an assembly ensures that your setup remains clean and scalable, reducing the need for repetitive code in your DbContext. By understanding and leveraging these configuration methods, you can ensure that your EF Core models are both flexible and easy to maintain, no matter the size and complexity of your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c2c47c1ac4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering EF Core Configuration: Part 2 — Exploring Data Annotations]]></title>
            <link>https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-2-exploring-data-annotations-24dbcab6e0f0?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/24dbcab6e0f0</guid>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dataannotations]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 14:03:23 GMT</pubDate>
            <atom:updated>2024-09-02T06:40:28.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering EF Core Configuration: Part 2 — Exploring Data Annotations</h3><h3>Introduction</h3><p>In our ongoing journey through the world of EF Core configurations, we’ve explored the foundational approaches of Code First and Database First, and how conventions can automatically set up your data models with minimal effort “<a href="https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-1-exploring-code-first-database-first-and-configuration-aa69fdafd4b6">Mastering EF Core Configuration: Part 1 — Exploring Code First, Database First, and Configuration Techniques</a>”. But what if you need more control, without diving deep into the Fluent API? That’s where <strong>Data Annotations</strong> come into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*k-LrZlzGX501IeBPxE4boQ.png" /><figcaption>Data Annotations</figcaption></figure><p>Data Annotations provide a simple powerful way to customize your EF Core models directly within your entity classes. By adding a few well-placed attributes, you can fine-tune how EF Core handles your data, from defining primary keys and relationships to setting validation rules and formatting options. This approach offers a middle ground between the ease of conventions and the flexibility of the Fluent API, making it an ideal choice for many developers.</p><p>In this article, we’ll dive into the most commonly used Data Annotations in EF Core, showing you how to apply them effectively to create more precise and maintainable data models. <strong>Whether you’re new to EF Core or looking to refine your skills</strong>, this guide will help you harness the power of Data Annotations to take your application to the next level.</p><h3>Data Annotations</h3><p>In Entity Framework Core (EF Core), Data Annotations provide a way to configure the data model by adding attributes to entity classes and their properties. These annotations offer a straightforward way to specify rules and behaviors directly within your code, often making the code more readable and maintainable. Here’s a detailed look at how to use Data Annotations for configuration:</p><h3>Common Data Annotations</h3><p>Here are some of the most commonly used data annotations in EF Core:</p><h4>[Key] Attribute:</h4><p>The <strong>[Key]</strong> attribute is used to specify the primary key of an entity.</p><pre>public class Product<br>{<br>    [Key]<br>    public int ProductId { get; set; } // Primary key<br>    public string Name { get; set; }<br>}</pre><p>It’s important to note that if you do not specify a <strong>[Key]</strong> attribute, EF Core will automatically use a property named <strong>Id </strong>or <strong>&lt;ClassName&gt;Id</strong> as the primary key by convention as we said before.</p><h4>[Required] Attribute:</h4><p>The <strong>[Required]</strong> attribute makes a property mandatory, meaning it cannot be null.</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [Required]<br>    public string Name { get; set; } // Non-nullable<br>}</pre><p><strong>Note:</strong> The <strong>[Required]</strong> attribute makes a property mandatory, meaning it cannot be null. However, for value types like <strong>int </strong>or <strong>decimal</strong>, which are non-nullable by default in C#, the <strong>[Required]</strong> attribute doesn&#39;t add any extra enforcement. These types can&#39;t be null anyway. For reference types like <strong>string </strong>or nullable value types like <strong>int?</strong>, the <strong>[Required]</strong> attribute ensures that these properties must have a value and cannot be null.</p><h4>[MaxLength] and [MinLength] Attributes:</h4><p>The <strong>[MaxLength]</strong> and <strong>[MinLength]</strong> attributes specify the maximum and minimum length of a string.</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [MaxLength(100)]<br>    public string Name { get; set; } // Max length of 100<br><br>    [MinLength(5)]<br>    public string Description { get; set; } // Min length of 5<br>}</pre><p><strong>Note: </strong>The <strong>[MinLength]</strong> attribute does not enforce length constraints at the database level; it is primarily used for validation purposes in ASP.NET Core MVC. The <strong>[MaxLength]</strong> attribute, however, does translate to database schema constraints, setting the maximum length of the column.</p><h4>[StringLength] Attribute:</h4><p>The <strong>[StringLength]</strong> attribute is a combination of <strong>[MaxLength]</strong> and <strong>[MinLength]</strong> for strings.</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [StringLength(100, MinimumLength = 5)]<br>    public string Name { get; set; } // Length between 5 and 100<br>}</pre><p><strong>Note: </strong>In newer versions of EF Core, the behavior of the <strong>[StringLength]</strong> attribute has evolved. While it was originally more focused on validation in ASP.NET MVC, in EF Core, it <strong>does</strong> influence the database schema by defining the maximum length of a column.</p><h4>[Column] Attribute:</h4><p>The <strong>[Column]</strong> attribute specifies the database column name and other properties like type and order.</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [Column(&quot;ProductName&quot;, TypeName = &quot;nvarchar(150)&quot;)]<br>    public string Name { get; set; } // Custom column name and type<br>}</pre><h4>[Table] Attribute:</h4><p>The <strong>[Table]</strong> attribute specifies the database table name for an entity.</p><pre>[Table(&quot;ProductsTable&quot;)]<br>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br>}</pre><p>Suppose you have an entity <strong>Product </strong>that you want to map to a table named <strong>ProductsTable </strong>in a schema called <strong>Inventory</strong>.</p><pre>using System.ComponentModel.DataAnnotations.Schema;<br><br>[Table(&quot;ProductsTable&quot;, Schema = &quot;Inventory&quot;)]<br>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br>}</pre><p>In this example, the <strong>Product </strong>entity is mapped to the <strong>ProductsTable </strong>within the <strong>Inventory </strong>schema. EF Core will generate queries that target <strong>Inventory.ProductsTable</strong> when querying or updating <strong>Product </strong>entities.</p><h4>[ForeignKey] Attribute:</h4><p>The <strong>[ForeignKey]</strong> attribute specifies the foreign key for a navigation property.</p><h4>— Example 1:</h4><pre>public class Order<br>{<br>    public int OrderId { get; set; }<br>    <br>    // Foreign key property<br>    [ForeignKey(&quot;Customer&quot;)]<br>    public int CustomerId { get; set; }</pre><h4>— Example 2:</h4><pre>public class Order<br>{<br>    public int OrderId { get; set; } <br><br>    // Foreign key property<br>    public int CustomerId { get; set; } <br><br>    // Navigation property<br>    [ForeignKey(&quot;CustomerId&quot;)]<br>    public Customer Customer { get; set; }<br>}<br><br>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public string Name { get; set; }<br>    public ICollection&lt;Order&gt; Orders { get; set; }<br>}</pre><h3>Advanced Scenarios: Navigating Complex Relationships in EF Core</h3><p>Up to this point, we’ve covered many of the fundamental Data Annotations that are essential for configuring your EF Core models. These attributes allow you to define keys, relationships, and validation rules with ease, making your data models more precise and maintainable. But as you delve deeper into more complex scenarios, you may encounter situations where the standard annotations aren’t enough. This is where special cases come into play.</p><h4>[InverseProperty] Attribute:</h4><p>The <strong>[InverseProperty]</strong> attribute is used to specify the inverse of a relationship. This is particularly useful in scenarios where there are multiple navigation properties between the same pair of entities, allowing EF Core to understand which navigation properties correspond to each other.</p><p>Imagine you’re building an application for a software company. Each employee can manage several projects, and at the same time, they might also work as a developer on other projects. In this case, you have two different relationships between the <strong>Employee </strong>and <strong>Project </strong>entities: one where the employee is the project manager and another where the employee is a developer.</p><p>Without the <strong>[InverseProperty]</strong> attribute, EF Core might get confused about which navigation properties correspond to each other, leading to incorrect mappings or errors. By explicitly specifying the inverse properties, you ensure that EF Core understands these relationships correctly.</p><p>For example, consider an employee named Alex. Alex manages three projects and is working as a developer on two others. The <strong>[InverseProperty]</strong> attribute allows you to clearly define these roles, so EF Core can properly track and manage Alex&#39;s involvement in these projects without any ambiguity.</p><p>In this scenario, <strong>[InverseProperty]</strong> is not just a convenience; it’s a necessity for ensuring that your data model accurately reflects the real-world relationships between employees and projects.</p><pre>public class Employee<br>{<br>    public int EmployeeId { get; set; }<br>    public string Name { get; set; }<br><br>    // Projects managed by the employee<br>    [InverseProperty(&quot;Manager&quot;)]<br>    public ICollection&lt;Project&gt; ManagedProjects { get; set; }<br><br>    // Projects the employee is working on<br>    [InverseProperty(&quot;Developer&quot;)]<br>    public ICollection&lt;Project&gt; DevelopedProjects { get; set; }<br>}<br><br>public class Project<br>{<br>    public int ProjectId { get; set; }<br>    public string Title { get; set; }<br>    public int ManagerId { get; set; }<br>    <br>    // Navigation property for the manager<br>    [InverseProperty(&quot;ManagedProjects&quot;)]<br>    public Employee Manager { get; set; }<br><br>    public int DeveloperId { get; set; }<br>    <br>    // Navigation property for the developer<br>    [InverseProperty(&quot;DevelopedProjects&quot;)]<br>    public Employee Developer { get; set; }<br>}</pre><h4>— Explanation</h4><ul><li><strong>ManagedProjects and Manager</strong>: The <strong>[InverseProperty(&quot;Manager&quot;)]</strong> attribute on <strong>ManagedProjects</strong> in the <strong>Employee </strong>class indicates that this collection of projects corresponds to the <strong>Manager </strong>navigation property in the <strong>Project </strong>class.</li><li><strong>DevelopedProjects and Developer</strong>: Similarly, the <strong>[InverseProperty(&quot;Developer&quot;)]</strong> attribute on <strong>DevelopedProjects </strong>in the <strong>Employee </strong>class specifies that these projects are related to the <strong>Developer </strong>navigation property in the <strong>Project </strong>class.</li></ul><h4>How EF Core Resolves Relationships?</h4><p>When EF Core processes these entities, the <strong>[InverseProperty]</strong> attribute ensures that it correctly pairs the <strong>ManagedProjects </strong>collection with the <strong>Manager </strong>property, and the <strong>DevelopedProjects </strong>collection with the <strong>Developer </strong>property. Without this attribute, EF Core might not automatically resolve these relationships correctly due to the multiple potential navigation properties between the entities.</p><h4>[ConcurrencyCheck] Attribute:</h4><p>The <strong>[ConcurrencyCheck]</strong> attribute is used to mark a property as part of the concurrency token for optimistic concurrency control.</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [ConcurrencyCheck]<br>    public decimal Price { get; set; }<br>}</pre><h3>What is Concurrency Control?</h3><p>Concurrency control in databases ensures that multiple transactions can occur simultaneously without causing inconsistencies or conflicts. In Entity Framework Core, <strong>optimistic concurrency control</strong> is used to detect conflicts between transactions. It assumes that conflicts are rare and allows transactions to proceed without locking resources until a conflict is detected.</p><h4>How it Works Internally?</h4><ol><li><strong>Read Operation</strong>: When a <strong>Product </strong>is read from the database, EF Core retrieves the current value of <strong>Price</strong>.</li><li><strong>Update Operation</strong>: When an update is attempted, EF Core generates an <strong>UPDATE </strong>statement with a <strong>WHERE </strong>clause that checks if the <strong>Price </strong>value in the database is the same as the one originally retrieved.</li><li><strong>Conflict Detection</strong>: If the <strong>Price </strong>value in the database has changed since it was last read (e.g., another user updated it), the <strong>WHERE </strong>clause will fail, resulting in a concurrency conflict.</li></ol><h4>— Scenario</h4><p>Imagine you have a <strong>Product </strong>entity that multiple users can update concurrently:</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [ConcurrencyCheck]<br>    public decimal Price { get; set; } // Concurrency token<br>    public string Name { get; set; }<br>}</pre><h4>Step-by-Step Concurrency Control:</h4><h4><strong>1. Read Operation</strong>:</h4><ul><li>A user (<strong>User A</strong>) retrieves a <strong>Product </strong>from the database.</li><li><strong>User A</strong> sees the <strong>Price </strong>is <strong>$20.00</strong>.</li></ul><h4><strong>2. Another Read Operation</strong>:</h4><ul><li>Before <strong>User A</strong> updates the <strong>Product</strong>, another user (<strong>User B</strong>) retrieves the same <strong>Product</strong>.</li><li><strong>User B</strong> also sees the <strong>Price </strong>as <strong>$20.00</strong>.</li></ul><h4><strong>3. Concurrent Update Attempt</strong>:</h4><ul><li><strong>User B</strong> updates the <strong>Price</strong> to <strong>$25.00</strong> and saves changes.</li><li>EF Core generates an <strong>UPDATE </strong>statement and includes the original <strong>Price </strong>(<strong>$20.00</strong>) in the <strong>WHERE </strong>clause:</li></ul><pre>UPDATE Products SET Price = 25.00 WHERE ProductId = 1 AND Price = 20.00;</pre><ul><li>Since the <strong>Price </strong>in the database is still <strong>$20.00</strong>, the update succeeds, and the <strong>Price </strong>is now <strong>$25.00</strong>.</li></ul><h4><strong>4. User A Attempts Update</strong>:</h4><ul><li><strong>User A</strong>, unaware of <strong>User B</strong>’s update, tries to change the <strong>Price </strong>to <strong>$22.00</strong> and saves changes.</li><li>EF Core generates an <strong>UPDATE </strong>statement with the original <strong>Price </strong>(<strong>$20.00</strong>) in the <strong>WHERE </strong>clause:</li></ul><pre>UPDATE Products SET Price = 22.00 WHERE ProductId = 1 AND Price = 20.00;</pre><ul><li>This time, the <strong>WHERE </strong>clause fails because the <strong>Price </strong>in the database is now <strong>$25.00</strong>, not <strong>$20.00</strong>.</li></ul><h4><strong>5. Concurrency Conflict</strong>:</h4><ul><li>Because the <strong>UPDATE </strong>statement&#39;s <strong>WHERE </strong>clause didn&#39;t match any rows (i.e., no row had <strong>Price = 20.00</strong>), EF Core detects a concurrency conflict and throws a <strong>DbUpdateConcurrencyException</strong>.</li></ul><h4>Handling Concurrency Conflicts</h4><p>When a concurrency conflict is detected, EF Core throws a <strong>DbUpdateConcurrencyException</strong>. You can handle this exception to inform users or take corrective action.</p><h4>Example</h4><pre>try<br>{<br>    context.SaveChanges();<br>}<br>catch (DbUpdateConcurrencyException ex)<br>{<br>    // Handle the concurrency conflict<br>    // For example, refresh the data and retry, or notify the user<br>    Console.WriteLine(&quot;Concurrency conflict detected.&quot;);<br>}</pre><h4>Summary</h4><ul><li><strong>[ConcurrencyCheck]</strong>: Marks a property as a concurrency token to help detect conflicting updates.</li><li><strong>Optimistic Concurrency</strong>: Assumes conflicts are rare and uses tokens to detect them during <strong>UPDATE </strong>or <strong>DELETE </strong>operations.</li><li><strong>Conflict Handling</strong>: EF Core throws a <strong>DbUpdateConcurrencyException </strong>when a conflict is detected, allowing you to handle it programmatically.</li></ul><h4>[Timestamp] Attribute:</h4><p>The <strong>[Timestamp]</strong> attribute is used to designate a property in your entity class as a row version, serving as a concurrency token. This token is used for optimistic concurrency control, which helps ensure that the data in your database is consistent, even when multiple users are updating the same data simultaneously.</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [Timestamp]<br>    public byte[] RowVersion { get; set; }<br>}</pre><h4>How Does [Timestamp] Work?</h4><p>The <strong>[Timestamp]</strong> attribute typically applies to a <strong>byte[]</strong> property that EF Core treats as a version number or timestamp. Each time a row is updated in the database, the version number is incremented or the timestamp is updated. If another process has modified the row since it was last read, the version numbers won&#39;t match, and EF Core will throw a <strong>DbUpdateConcurrencyException</strong>.</p><h4>Step-by-Step Explanation with Example:</h4><h4>— Scenario</h4><p>Imagine you have a <strong>Product </strong>entity, and you want to ensure that updates to the <strong>Product </strong>are controlled to avoid overwriting changes made by other users.</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br><br>    [Timestamp]<br>    public byte[] RowVersion { get; set; } // Concurrency token<br>}</pre><h4><strong>1. Reading the Entity</strong>:</h4><ul><li>A user (User A) reads a Product from the database. The RowVersion value is also retrieved, let&#39;s say it&#39;s 0x000000000001.</li></ul><h4><strong>2. Another Read Operation</strong>:</h4><ul><li>Before User A updates the Product, another user (User B) reads the same Product and gets the same RowVersion, 0x000000000001.</li></ul><h4><strong>3. User B Updates the Product</strong>:</h4><ul><li>User B updates the Price of the Product and saves changes.</li><li>EF Core generates an UPDATE statement, including the RowVersion in the WHERE clause to ensure the version matches:</li></ul><pre>UPDATE Products SET Price = 25.00, RowVersion = NEW_ROW_VERSION <br>WHERE ProductId = 1 AND RowVersion = 0x000000000001;</pre><ul><li>The RowVersion is updated to 0x000000000002 (or another new version) in the database.</li></ul><h4><strong>4. User A Attempts Update</strong>:</h4><ul><li>User A, unaware of User B’s update, tries to change the Price to $22.00 and saves changes.</li><li>EF Core generates an UPDATE statement with the original RowVersion (0x000000000001) in the WHERE clause:</li></ul><pre>UPDATE Products SET Price = 22.00, RowVersion = NEW_ROW_VERSION <br>WHERE ProductId = 1 AND RowVersion = 0x000000000001;</pre><ul><li>Since the RowVersion in the database is now 0x000000000002, not 0x000000000001, the WHERE clause fails.</li></ul><h4><strong>5. Concurrency Conflict</strong>:</h4><ul><li>Because the WHERE clause did not match any rows (as the version number changed), EF Core detects a concurrency conflict and throws a <strong>DbUpdateConcurrencyException</strong>.</li></ul><h4>Handling Concurrency Conflicts</h4><p>You can catch the DbUpdateConcurrencyException in your code to handle the conflict:</p><pre>try<br>{<br>    context.SaveChanges();<br>}<br>catch (DbUpdateConcurrencyException ex)<br>{<br>    // Handle the concurrency conflict<br>    Console.WriteLine(&quot;Concurrency conflict detected. The record was modified by another user.&quot;);<br><br>    // Optionally, refresh the entity from the database<br>    var entry = ex.Entries.Single();<br>    entry.Reload();<br>    // Inform the user or log the conflict<br>}</pre><h3>Timestamp VS ConcurrencyCheck Attributes</h3><p>The <strong>[Timestamp]</strong> and <strong>[ConcurrencyCheck]</strong> attributes in Entity Framework Core (EF Core) are both used for concurrency control as we said before, but they serve different purposes and are used in different scenarios. Here&#39;s a detailed explanation of each as a recap, along with guidance on when to use them.</p><h4>[Timestamp] Attribute:</h4><h4>Purpose</h4><p>The <strong>[Timestamp]</strong> attribute as we said before is used to designate a property as a concurrency token for optimistic concurrency control. It is typically applied to a <strong>byte[]</strong> property that represents a version or timestamp in the database. This token is used to detect if the data has been modified since it was last read.</p><h4>Characteristics</h4><ul><li><strong>Data Type</strong>: Usually applied to a <strong>byte[]</strong> property, which acts as a version or timestamp.</li><li><strong>Automatic Handling</strong>: EF Core automatically updates this property with a new value every time a record is modified.</li><li><strong>Database Support</strong>: Supported by databases that provide timestamp or row version features (e.g., SQL Server’s <strong>rowversion </strong>type).</li></ul><h4>Usage</h4><ul><li><strong>Single Concurrency Token</strong>: Best used when you want a single property to handle concurrency checks for the entire entity.</li><li><strong>Automatic Versioning</strong>: Ideal for entities where automatic versioning is supported by the database.</li><li><strong>High-traffic Systems</strong>: Suitable for scenarios where multiple properties might be updated frequently, ensuring overall consistency with a single token.</li></ul><h4>— Example</h4><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br><br>    [Timestamp]<br>    public byte[] RowVersion { get; set; } // Concurrency token<br>}</pre><h4>[ConcurrencyCheck] Attribute:</h4><h4>Purpose:</h4><p>The <strong>[ConcurrencyCheck]</strong> attribute is used to mark one or more specific properties as concurrency tokens. It ensures that a property or set of properties hasn&#39;t changed between when it was read and when an update is attempted.</p><h4>Characteristics:</h4><ul><li><strong>Multiple Properties</strong>: Can be applied to multiple properties in an entity.</li><li><strong>Manual Handling</strong>: Each marked property is individually checked for changes.</li><li><strong>Flexible Use</strong>: Allows you to control concurrency checks at a more granular level compared to <strong>[Timestamp]</strong>.</li></ul><h4>Usage:</h4><ul><li><strong>Specific Property Tracking</strong>: Use when you want to track concurrency on specific properties rather than the entire entity.</li><li><strong>Complex Models</strong>: Useful in scenarios where different properties have different significance, and only certain changes need to be tracked.</li><li><strong>Multiple Checks</strong>: Can be applied to multiple properties when different parts of an entity may be updated independently.</li></ul><h4>— Example</h4><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [ConcurrencyCheck]<br>    public decimal Price { get; set; } // Concurrency token for this property<br><br>    [ConcurrencyCheck]<br>    public string Name { get; set; } // Another concurrency token for this property<br>}</pre><h4>When to Use Each?</h4><h4><strong>Use </strong><strong>[Timestamp]</strong>:</h4><ul><li>When you want a single, unified way to check for concurrency across the entire entity.</li><li>When the database supports timestamp or row versioning, allowing for efficient concurrency management.</li><li>When dealing with entities that frequently undergo changes to multiple properties, making a single version check more efficient.</li></ul><h4><strong>Use </strong><strong>[ConcurrencyCheck]</strong>:</h4><ul><li>When you need to control concurrency checks at the property level.</li><li>When you want to ensure specific properties have not changed during an update.</li><li>When your database does not support automatic versioning, or you prefer a more fine-grained approach.</li></ul><h3>Advantages of Data Annotations</h3><ul><li><strong>Simplicity</strong>: Data Annotations provide a simple way to apply configuration directly in the entity class.</li><li><strong>Readability</strong>: They keep configuration close to the code, making it easier to read and maintain.</li><li><strong>Ease of Use</strong>: Ideal for straightforward scenarios and common configurations.</li></ul><h3>Limitations of Data Annotations</h3><ul><li><strong>Limited Flexibility</strong>: They cover basic configurations but may not handle complex scenarios.</li><li><strong>Clutter</strong>: Can lead to cluttered code if overused, especially with complex models.</li></ul><h3>Combining Data Annotations with Fluent API</h3><p>In scenarios where Data Annotations are not sufficient, you can combine them with the Fluent API to achieve more complex configurations. The Fluent API offers greater flexibility and can override Data Annotations when there is a conflict.</p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Product&gt;()<br>        .Property(p =&gt; p.Name)<br>        .IsRequired()<br>        .HasMaxLength(100);<br>}</pre><p>Both Data Annotations and the Fluent API are used to configure the model. However, if there’s a conflict between a Data Annotation and a Fluent API configuration, the Fluent API takes precedence. This allows you to start with simple configurations using Data Annotations and then refine or override those configurations using the more powerful and flexible Fluent API.</p><h4>— Example:</h4><p>Let’s say you have a <strong>Product </strong>entity with a <strong>Name </strong>property. You use the <strong>[MaxLength]</strong> attribute to set a maximum length of 100 characters:</p><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br><br>    [MaxLength(100)]<br>    public string Name { get; set; }<br>}</pre><p>However, later in the <strong>OnModelCreating </strong>method, you decide that the maximum length should actually be 50 characters. You can override the <strong>[MaxLength(100)]</strong> annotation with the Fluent API like this:</p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Product&gt;()<br>        .Property(p =&gt; p.Name)<br>        .HasMaxLength(50);  // This will override the Data Annotation<br>}</pre><h4>What Happens?</h4><ul><li>The <strong>[MaxLength(100)]</strong> annotation initially sets the maximum length for the <strong>Name </strong>column to 100 characters.</li><li>The Fluent API configuration in <strong>OnModelCreating </strong>then overrides this, setting the maximum length to 50 characters instead.</li><li>As a result, the final database schema will enforce a maximum length of 50 characters for the <strong>Name </strong>column.</li></ul><h4>Why This Matters?</h4><p>Understanding that the Fluent API takes precedence is important because it allows you to centralize and manage complex configurations in one place, avoiding potential conflicts and confusion. While Data Annotations are convenient for simple, inline configurations, the Fluent API provides a more comprehensive and flexible approach, especially for scenarios where global changes or advanced configurations are needed. By knowing that the Fluent API will override Data Annotations, you can ensure that your final configuration is consistent and intentional, reducing the risk of conflicting settings in your model.</p><h3>Conclusion</h3><p>In this article, we’ve taken a closer look at Data Annotations in EF Core, exploring how they provide a simple powerful way to configure your data models. From defining primary keys and relationships to handling complex scenarios like concurrency control, Data Annotations offer a convenient way to fine-tune your entities directly within your code. While they excel in simplicity and readability, they do have their limitations, especially when it comes to more advanced configurations.</p><p>As we continue our journey through EF Core configurations, it’s time to dive into the more flexible and powerful world of the Fluent API. In the next part of this series, we’ll explore how the Fluent API allows you to achieve configurations that go beyond the capabilities of Data Annotations, giving you full control over your data models. Stay tuned as we unlock the next level of mastery in EF Core.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24dbcab6e0f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering EF Core Configuration: Part 1 — Exploring Code First, Database First, and Configuration…]]></title>
            <link>https://medium.com/@yayasaafan/mastering-ef-core-configuration-part-1-exploring-code-first-database-first-and-configuration-aa69fdafd4b6?source=rss-a54035c59095------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa69fdafd4b6</guid>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[ef-core-configuration]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Yahia Saafan]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 11:12:21 GMT</pubDate>
            <atom:updated>2024-08-25T11:12:21.828Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering EF Core Configuration: Part 1 — Exploring Code First, Database First, and Configuration Techniques</h3><h3>Introduction</h3><p>In our last story, we took a deep dive into the world of Entity Framework Core, focusing on the DbContext “<a href="https://medium.com/@yayasaafan/mastering-dbcontext-in-entity-framework-core-configuration-lifetime-and-best-practices-e8e89037d34d">Mastering DbContext in Entity Framework Core: Configuration, Lifetime, and Best Practices</a>”— a key part of how your application connects to the database. We explored how to set it up, manage its lifetime, and make the most of its capabilities. Now that you’re familiar with DbContext and how it works, it’s the perfect time to move on to the next important topic: configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*fugPZ_0Y7wAhy0ihI1G4Lg.jpeg" /></figure><p>Configurations in EF Core are like the rules and guidelines that tell your application how to interact with the database. They help you map your data models to the database, ensuring everything runs smoothly. But before we jump into the details of these configurations, it’s important to understand the different ways you can approach development in EF Core — specifically, <strong>Code First</strong> and <strong>Database First</strong>.</p><p>In this article, we’ll start by looking at these two approaches, helping you understand when and why you might choose one over the other. Once we have that foundation, we’ll begin exploring the various configurations you can use in EF Core to build efficient and reliable applications.</p><p>Let’s start this journey together, step by step, making sure everything is clear and easy to follow.</p><h3>1. Code First</h3><p><strong>Code First</strong> is an approach where you define your data model using <strong>C#</strong> classes, and EF Core generates the database schema from these classes. This approach is often used when starting a new project or when you want to have full control over the code.</p><h4>Advantages</h4><ul><li><strong>Control Over Code</strong>: You have full control over your entity classes, allowing for a clean and maintainable codebase.</li><li><strong>Migration Support</strong>: Easily manage database schema changes with migrations.</li><li><strong>No Initial Database Required</strong>: You don’t need an existing database to start; EF Core will create it for you.</li></ul><h4>How It Works</h4><ol><li><strong>Define Entities</strong>: Create C# classes representing your entities.</li><li><strong>Configure DbContext</strong>: Set up your <strong>DbContext</strong> to manage these entities.</li><li><strong>Use Migrations</strong>: Use EF Core’s migrations to create and update the database schema.</li></ol><h4>Example:</h4><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br>}<br><br>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Product&gt; Products { get; set; }<br><br>    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)<br>    {<br>        optionsBuilder.UseSqlServer(&quot;YourConnectionStringHere&quot;);<br>    }<br>}</pre><p>To create the database, you would use:</p><pre>dotnet ef migrations add InitialCreate<br>dotnet ef database update</pre><h3>2. Database First</h3><p><strong>Database First</strong> is used when you have an existing database, and you want to generate entity classes and the DbContext based on that schema. This is useful for working with <strong>legacy databases</strong>.</p><h4>Advantages</h4><ul><li><strong>Works with Existing Databases</strong>: Ideal for projects where the database schema is already defined.</li><li><strong>Automatic Code Generation</strong>: EF Core can generate the data model for you.</li></ul><h4>How It Works</h4><ol><li><strong>Scaffold Model</strong>: Use EF Core tools to scaffold a model from an existing database.</li><li><strong>Generated Code</strong>: EF Core generates the <strong>DbContext</strong> and entity classes that map to the existing database tables.</li></ol><h4>Example</h4><p>You can use the following command to scaffold the model:</p><pre>dotnet ef dbcontext scaffold &quot;YourConnectionStringHere&quot; Microsoft.EntityFrameworkCore.SqlServer -o Models</pre><p>This command will generate the entity classes and <strong>DbContext</strong> in the specified output directory (e.g., <strong>Models</strong>).</p><h3>Understanding EF Core Configurations: From Conventions to Fluent API</h3><p>Now that we’ve explored the two primary approaches — Code First and Database First — it’s time to dive into the specifics of configuring your EF Core models. Whether you’re building your database from scratch or working with an existing schema, understanding how to configure your models is essential for creating efficient and maintainable applications. EF Core provides a variety of ways to define these configurations, from leveraging conventions that automatically set up your model based on naming patterns, to using the more precise and flexible Fluent API. Let’s start by exploring how EF Core configurations work behind the scenes, beginning with the default behavior, known as <strong>Configuration by Convention</strong>.</p><h3>Configuration by Convention</h3><p>EF Core uses conventions to automatically configure the data model based on the names and types of the properties in your entity classes. Conventions are the default behavior and require the least amount of code.</p><h4>Key Conventions:</h4><h4><strong>1. Primary Key</strong></h4><p>EF Core assumes a property named <strong>Id</strong> or <strong>&lt;EntityName&gt;Id</strong> is the PK.</p><pre>public class Product<br>{<br>    public int ProductId { get; set; } // Assumed to be the primary key<br>    public string Name { get; set; }<br>}<br></pre><h4><strong>2. Foreign Key</strong></h4><p>A property named <strong>&lt;NavigationPropertyName&gt;Id</strong> is assumed to be a FK.</p><pre>public class Order<br>{<br>  public int OrderId { get; set; }<br>  public int CustomerId { get; set; } // Assumed to be a foreign key<br>  public Customer Customer { get; set; } // Navigation property to customer<br>}</pre><h4><strong>3. Relationships</strong></h4><p>Navigation properties define relationships between entities. EF Core will infer the type of relationship based on the navigation properties and their types.</p><pre>public class Customer<br>{<br>    public int CustomerId { get; set; }<br>    public ICollection&lt;Order&gt; Orders { get; set; } // One-to-many relationship<br>}</pre><h4><strong>4. Naming Conventions</strong></h4><p>Table and column names default to the entity and property names.</p><p><strong>Note: </strong>Pluralization is not applied by default in EF Core.</p><h4><strong>5. Cascade Delete</strong></h4><p>EF Core configures cascade delete behavior for required relationships (i.e., relationships where the foreign key is non-nullable).</p><h3>Configuration Using the Fluent API</h3><p>The Fluent API provides a way to configure the EF Core model with more precision and flexibility than conventions alone. It is typically used in the <strong>OnModelCreating</strong> method of the <strong>DbContext</strong>.</p><h4>Fluent API Examples:</h4><ul><li><strong>Primary Key Configuration:</strong> Specify the primary key explicitly.</li></ul><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Product&gt;()<br>        .HasKey(p =&gt; p.ProductId);<br>}</pre><ul><li><strong>Foreign Key Configuration:</strong> Define foreign keys explicitly.</li></ul><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Order&gt;()<br>        .HasOne(o =&gt; o.Customer)<br>        .WithMany(c =&gt; c.Orders)<br>        .HasForeignKey(o =&gt; o.CustomerId);<br>}</pre><ul><li><strong>Table and Column Naming:</strong> Customize table and column names.</li></ul><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Product&gt;()<br>        .ToTable(&quot;ProductsTable&quot;)<br>        .Property(p =&gt; p.Name)<br>        .HasColumnName(&quot;ProductName&quot;);<br>}</pre><ul><li><strong>Composite Keys:</strong> Define composite primary keys.</li></ul><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;OrderDetail&gt;()<br>        .HasKey(od =&gt; new { od.OrderId, od.ProductId });<br>}</pre><ul><li><strong>Index Configuration:</strong> Define indexes for specific columns.</li></ul><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Product&gt;()<br>        .HasIndex(p =&gt; p.Name)<br>        .HasDatabaseName(&quot;IX_Product_Name&quot;);<br>}</pre><h3>Conclusion</h3><p>In this first part of our journey through EF Core configurations, we’ve explored the foundational approaches of <strong>Code First</strong> and <strong>Database First</strong> — two powerful methods for structuring your application’s interaction with the database. Understanding these approaches is crucial as they set the stage for how you’ll configure your models in EF Core.</p><p>We’ve also touched on the automatic conventions that EF Core uses to simplify the configuration process, demonstrating how much can be achieved with minimal effort. However, as your application grows and your requirements become more complex, relying solely on conventions may not be enough. That’s when you’ll need to take a closer look at more advanced configuration techniques.</p><p>Before we dive into the detailed world of the <strong>Fluent API</strong>, our next stop will be <strong>Data Annotations</strong> — a simpler, yet powerful way to customize your models directly within your entity classes. Data Annotations offer a convenient method to override EF Core’s default conventions without the need for extensive code. In the next story, we’ll explore how to use Data Annotations effectively to fine-tune your configurations, setting the stage for more advanced Fluent API techniques later on.</p><p>Stay tuned as we continue to unlock the full potential of EF Core configurations. Whether you’re just starting out or looking to refine your skills, there’s much more to discover on this journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa69fdafd4b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>