<?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 Mohamed Ali  on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Ali  on Medium]]></description>
        <link>https://medium.com/@mohamed.ali.21?source=rss-2774b5c2a11f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yNHKnp_dK9XlO3e-2yPGuA.jpeg</url>
            <title>Stories by Mohamed Ali  on Medium</title>
            <link>https://medium.com/@mohamed.ali.21?source=rss-2774b5c2a11f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:11:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamed.ali.21/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[How to Redesign a Production Database Table Without Breaking Everything]]></title>
            <link>https://medium.com/@mohamed.ali.21/how-to-redesign-a-production-database-table-without-breaking-everything-d02ab43abf75?source=rss-2774b5c2a11f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d02ab43abf75</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[databas]]></category>
            <dc:creator><![CDATA[Mohamed Ali ]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 14:00:36 GMT</pubDate>
            <atom:updated>2026-04-19T14:00:36.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiynTAX-fVfT7GrptNprwA.png" /></figure><p>At some point, every system ends up with a table that needs serious work. Not a new column or a quick index — a proper redesign. The kind where you look at the schema and wonder what the original developer was thinking (even if that developer was you).</p><p>Changing the code around it is straightforward. Changing the data inside it, in a live system, without breaking anything — that’s the actual problem. Here’s how to approach it without turning a schema cleanup into an incident.</p><h3>Why the “Just Run the Migration” Approach Fails</h3><p>Letting your ORM generate migrations feels fine — change the model, generate the file, apply it. And most of the time, it works.</p><p>The problem shows up when you’re making bigger structural changes. Your ORM might generate something like:</p><pre>DROP TABLE Products;<br>CREATE TABLE Products (...);</pre><p>Letting that run will wipe whatever data is already in that table. And even when it doesn’t go that far, changing column types or restructuring relationships can cause table locks, unexpected downtime, or data corruption that nobody notices until something breaks downstream.</p><p>The problem isn’t migrations themselves. It’s treating a schema change the same way you treat a code deployment.</p><h3>The Expand → Migrate → Contract Pattern</h3><p>The core idea: never modify a heavily-used table in place. Introduce the change gradually, across multiple deployments, so you always have a working system and a way back.</p><h3>Expand — Add the New Structure</h3><p>Create the new table alongside the old one. Don’t touch anything that’s currently running.</p><pre>Products        ← live, untouched<br>Products_New    ← new design, empty</pre><p>Your app keeps running against the old schema. Users notice nothing. You’ve given yourself room to work carefully.</p><h3>Migrate — Move the Existing Data</h3><p>Backfill the old records into the new structure:</p><pre>INSERT INTO Products_New (Title, Cost)<br>SELECT Name, Price FROM Products;</pre><p>If the table has millions of rows, batch this. Running it as a single statement will lock the table and cause performance issues for everything else hitting the database at the same time.</p><h3>Handle Live Traffic — The Step Most People Get Wrong</h3><p>While you’re backfilling, your application is still running and writing new records to the old table. By the time the backfill finishes, those new records aren’t in the new table yet.</p><p>You have two options here, and neither is universally better — it depends on your situation:</p><p><strong>Short maintenance window:</strong> Pause writes, run the migration, bring the app back up. Simple, clean, and easier to reason about. Works well when you can afford even a few minutes of downtime.</p><p><strong>Dual writes:</strong> Write to both tables simultaneously during the transition. This avoids downtime, but it introduces its own risks — if a write succeeds on one table and fails on the other, you’ve got inconsistent data. You’ll need a clear strategy for handling that case before you go this route.</p><p>There’s no shortcut here. Pick the option that matches your downtime tolerance and make sure you’ve thought through the failure cases.</p><h3>Switch Reads</h3><p>Once the new table is fully caught up, update your application to read from it. Keep the old table in place for now — you’re just not actively using it anymore.</p><h3>Contract — Clean Up</h3><p>Before you drop the old table, don’t just wait a few days and assume it’s safe. Check your logs and confirm that no queries are still hitting it. Verify that no foreign keys are still pointing to it. Make sure nothing external — reporting tools, integrations, stored procedures — is reading from it directly. Take a backup before you drop anything.</p><p>Once you’re confident, drop the old table. As for renaming the new one back to the original name: sometimes it makes sense, but often it’s cleaner to just update your codebase to reference the new name and leave it. Renaming a table can quietly break ORM mappings, stored procedures, and anything else that references the table name directly.</p><p>Finally, I would like to thank you for reading and see you in another<br>article 💙👋</p><h3>And don’t forget to follow me on LinkedIn</h3><p><a href="https://www.linkedin.com/in/mohamed-ali-software-engineer/">Mohamed Ali | LinkedIn 😎</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d02ab43abf75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Tips to improve Entity Framework Performance ⚡]]></title>
            <link>https://medium.com/@mohamed.ali.21/5-tips-to-improve-entity-framework-performance-68c4a2622fa9?source=rss-2774b5c2a11f------2</link>
            <guid isPermaLink="false">https://medium.com/p/68c4a2622fa9</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mohamed Ali ]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 00:01:28 GMT</pubDate>
            <atom:updated>2026-04-19T14:03:15.596Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hello guys, I’m Mohamed Ali and today we will talk about the performance of Entity Framework and how to improve it.</em></p><p>Many of us deal with EF Core on a daily basis, so we should take some tips to create high-performance queries.</p><h3>1. Disable entity tracking if you don’t need it</h3><p>As you know, when you retrieve data from the database, the entity framework tracks any changes that occur in that data for you to update in the database once the changes are saved.</p><p>For better performance when retrieving read-only, not for modify it, there is no need to keep track of the object. So disable object tracking</p><p>Here is an example showing the performance of getting all data from the database <strong><em>with entities tracking Then with no tracking of entities using AsNoTracking() Method</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2FFdpDsY7vEiFFJQeObUg.png" /><figcaption>Tracking Entities VS No Tracking Entities</figcaption></figure><p>note : the default style for entity framework is track entities</p><h3>2. Avoid filtering data in memory</h3><p>There are some people who want to retrieve some data from a database using a specific condition, but they do not filter this data during the query from the database. Instead, they load all the data into memory and then filter it, meaning that the data is filtered in memory after executing the query. This is a very bad practice because you are retrieving data from the database that you do not need and storing it in memory, then performing filtering operations on it, which leads to very poor performance</p><p>This happens because the Where method is called after calling the ToList method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWjcDAKFTjWUy4K9ULDrwQ.png" /></figure><h3>3. Selecting only needed data</h3><p>Some people, when they want to retrieve data from certain columns in a database, they load all the columns from the database into memory first and then select the required columns and that will result in very bad performance because in this case you are loading data into memory that you don’t need, and then filtering it out</p><p>For better performance you just have to specify which columns you need to get from the database , This is by using the <strong><em>Select()</em></strong> method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBamP4PaR1UF31BwKOB-8g.png" /></figure><h3>4. Avoiding N + 1 Query Problem</h3><p>The “n+1 query problem” is a performance issue that occurs when an application executes a separate database query for each entity in a collection to retrieve related data. This means that if there are n entities in the collection, then n+1 queries will be executed, which can lead to inefficient performance, especially when dealing with large datasets</p><p>One of the best solutions to avoid this problem is to use eager loading so that only one query is sent to get the authors and their associated books</p><h4>The following image shows an example of this problem :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArW8NTbnSlm2nMA3NmmkJw.png" /></figure><h3>5. Use Skip and Take if you’re getting data for pages</h3><p>If you want to get the data in order to display it on the client page, and the client is dividing the data on multiple pages, as shown in the following image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*ZuSFFN1EYGdBpG0clrt-wg.png" /></figure><p>It is better not to retrieve all the data from the database in one go and then have the client split it into multiple pages.</p><p>But it is better to retrieve only the data needed for the current page by having the client send a request every time it goes from the current page to the next page.</p><p>The client sends the page number and the number of elements to display within it</p><p>We will handle this case using <strong><em>Take() </em></strong>&amp; <strong><em>Skip()</em></strong> methods as shown in the following image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhfr-qxs8WwHrUyLiXdvuQ.png" /></figure><h3>The End</h3><p>In the end, I would say that Entity Framework is very powerful and can send high performance queries, but that is if handled properly</p><p>So never stop looking for best practices in the entity framework</p><p>Finally, I would like to thank you for reading and see you in another <br>article 💙👋</p><h4>And don’t forget to follow me on linkedIn</h4><p><a href="https://www.linkedin.com/in/mohamed-ali-6955a6209/">Mohamed Ali | LinkedIn</a> 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68c4a2622fa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Request Processing Pipeline]]></title>
            <link>https://medium.com/@mohamed.ali.21/asp-net-request-processing-pipeline-eadec63c9429?source=rss-2774b5c2a11f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eadec63c9429</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[middleware]]></category>
            <dc:creator><![CDATA[Mohamed Ali ]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 14:39:07 GMT</pubDate>
            <atom:updated>2023-11-04T00:05:46.892Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hello everyone, i`m mohamed ali and i`ll talking today about the request processing pipeline in asp.net</em></p><h3>How is the request processed ?</h3><p>ASP.NET processes incoming HTTP requests through a pipeline of middleware components. The pipeline is made up of various components, each of which can perform a specific action on the request or response.</p><h4><strong><em>So what is middleware ?</em></strong></h4><blockquote><strong>Middleware is small software that handles requests and responses and be in program class in asp.net web application.</strong></blockquote><blockquote>Middleware are called in the order in which they are configured in the pipeline.. Also, middleware is bi-directional because it handles requests and responses</blockquote><blockquote>Once the request is executed, the response passes through the same middleware in reverse order</blockquote><p><strong>This is evidenced by this graph :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEQ6ClNsMh7vNaKptEIcsA.png" /></figure><p>To make things more clear, we will now create empty asp.net application with 3 middleware and then send a request to see how it will be handled by these middlewares</p><p><strong>Each middleware will handle the request and response as follows :</strong></p><ol><li><strong><em>First Middleware : <br></em></strong>In the request : <strong><em>first middleware (Request</em></strong>) will be printed<strong><em><br></em></strong>In the response : <strong><em>first middleware (Response</em></strong>) will be printed</li><li><strong><em>Second Middleware : <br></em></strong>In the request : <strong><em>second middleware (Request</em></strong>) will be printed<strong><em><br></em></strong>In the response : <strong><em>second middleware (Response</em></strong>) will be printed</li><li><strong><em>Third Middleware : <br></em></strong>In the request : <strong><em>third middleware (Request</em></strong>) will be printed<strong><em><br></em></strong>In the response : <strong><em>third middleware (Response</em></strong>) will be printed</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vmo2lkdWJWTHx_yDk1tbHA.png" /></figure><p>As shown in the previous image The middleware handles the request in the order in which they are configured in the pipeline, but will handle the response in the reverse order</p><p>So while sending a request, the result in the browser will be as follows ..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzrWt29H135YWDBrMRoOEA.png" /></figure><h4>How to create custom middleware</h4><p>Now that we know how the middleware is called in the request and the response, let’s learn how to create a custom middleware to solve the following problem :</p><blockquote>In any application, any exception error can occur, but this error appears in the api response in a way that is difficult to understand, as shown in the following picture</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vo8R6h2u9mI_wcZQG-iAZA.png" /><figcaption>API response before exception handling</figcaption></figure><p>So we want to create a simple middleware to handle the exception error and return the error message in the response, this is done through the following steps ..</p><h4>Step 1-&gt; Create Middleware Class</h4><p>Create a new class named <strong><em>ExceptionHandleMiddlewares.cs</em></strong> that will be inherited from the <strong><em>IMiddleware</em></strong> interface</p><pre><br>public class ExceptionHandleMiddlewares: IMiddleware<br>{<br>    public Task InvokeAsync(HttpContext context, RequestDelegate next)<br>    {<br>        throw new NotImplementedException();<br>    }<br>}</pre><h4>Step 2-&gt; Implement the InvokeAsync Method</h4><blockquote>You must implement the InvokeAsync method that is defined in the IMiddleware interface, then this method will be executed when the middleware is called.</blockquote><p>The invokeAsync method receives two parameters, Look at the following picture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-4noAmdztK05DVa-zwsSg.png" /><figcaption>InvokeAsync method</figcaption></figure><blockquote><strong>Arrow (1)</strong> : Indicates the first parameter <strong><em>(context) </em></strong>of type <strong><em>HttpContext</em></strong> and it encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP request is received.</blockquote><blockquote><strong>Arrow (2) </strong>: Indicates the second (next) parameter of type <strong><em>RequestDelegate</em></strong> and denotes the next middleware.</blockquote><blockquote><strong>Arrow (3) </strong>: Indicates the next middleware call point,<br>You must write the code to handle the request before the next middleware call, but the code to handle the response will be written after the next middleware call.</blockquote><p><strong>Now that we know what the InvokeAsync method is, let’s implement the exception handling logic.</strong></p><p>The first thing we will use is the keyword <strong><em>(try and catch)</em></strong> and the main target of it is to catch the exception error</p><p>In the (try) block we will call the next middleware by the (next) parameter, and In the <strong><em>(catch)</em></strong> block, we will execute the following steps :</p><ol><li>Update the status code to <strong><em>InternalServerError(500)</em></strong></li><li>Update the content type to <strong><em>application/json</em></strong></li><li>create a new object with two properties <strong><em>(StatusCode, ErrorMessage)</em></strong> and then write this object in the response body</li></ol><pre>public async Task InvokeAsync(HttpContext context, RequestDelegate next)<br>{<br>    try<br>    {<br>        await next(context);<br>    }<br>    catch (Exception ex)<br>    {<br>        // Update status code and content type<br>        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;<br>        context.Response.ContentType = &quot;application/json&quot;;<br>        <br>        // Create the response object<br>        var response = new<br>        {<br>            StatusCode = (int)HttpStatusCode.InternalServerError,   <br>            ErrorMessage = ex.Message<br>        };<br>        var json = JsonSerializer.Serialize(response);<br>        await context.Response.WriteAsync(json);<br>    }<br>}</pre><blockquote>Note : You can also log this exception</blockquote><h4>Step 3-&gt; Register Middleware Class</h4><p>register this middleware in <strong><em>(program.cs)</em></strong> is necessary so that it used in the application dependency injection container. This allows the middleware to be added to the request pipeline.</p><pre>// add middleware class to application services<br>builder.Services.AddScoped&lt;ExceptionHandleMiddleware&gt;();</pre><p><strong><em>(AddScoped) </em></strong>is used, it’s because the middleware class has dependencies that should be scoped to the request. Specifically, the HttpContext and the RequestDelegate should be created per request. By using AddScoped, the dependency injection container will create a new instance of the middleware class for each request, ensuring that the dependencies are correctly scoped</p><p>If you were to use (<strong><em>AddSingleton)</em></strong>, the same instance of the middleware would be used for all requests, which would result in incorrect behavior as well</p><p>Therefore, using (<strong><em>AddScoped) </em></strong>is the appropriate choice for scoping the middleware’s dependencies correctly to the request</p><h4>Step 4-&gt; Add Middleware To Request Pipeline</h4><p>By adding <strong><em>ExceptionHandleMiddleware</em></strong> to the pipeline, it will be executed for every incoming HTTP request and handle any unhandled exceptions that occur in subsequent middleware components</p><pre>// Add it as the first middleware in the order pipeline <br>app.UseMiddleware&lt;ExceptionHandleMiddleware&gt;();</pre><p>You can also write an extension method to this middleware :</p><pre>public static class CustomMiddlewaresExtensions<br>{<br>    public static IApplicationBuilder UseExceptionHandleMiddleware(this IApplicationBuilder app)<br>    {<br>        return app.UseMiddleware&lt;ExceptionHandleMiddleware&gt;();<br>    }<br>}</pre><p>Then call this method in the request pipeline</p><pre>// Add it as the first middleware in the order pipeline <br>app.UseExceptionHandleMiddleware();</pre><p>We have now created a custom middleware to handle any exception error that occurs in the application, so this will be the result of any exception error that occurs in the application ..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ec-iLDP66sJ1AoWi8niJiQ.png" /><figcaption>API response after exception handling</figcaption></figure><h4>The most popular middleware in ASP.NET</h4><p>There are also ready-made middleware for use in Asp.net , <br>Most used :</p><ol><li><strong><em>Authentication Middleware </em></strong>: Used to authenticate users and protect resources in an application.</li><li><strong><em>Routing middleware </em></strong>: These are used to route incoming requests to the appropriate controllers and procedures.</li><li><strong><em>Session middleware </em></strong>: used to store user session data.</li><li><strong><em>Static file middleware </em></strong>: used to serve static files, such as HTML, CSS, and JavaScript files.</li><li><strong><em>Error handling middleware </em></strong>: Used to handle errors that occur during request processing.</li><li><strong><em>CORS Middleware </em></strong>: Used to enable cross-origin resource sharing (CORS) in an application.</li><li><strong><em>Logging middleware </em></strong>: used to log information about requests and responses.</li><li><strong><em>Map Controller Middleware</em></strong> : it is used to map HTTP requests to controller actions.</li></ol><p>Thank you for reading 👍💛</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eadec63c9429" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>