<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ali Shahriari (MasterPars)</title>
    <description>The latest articles on DEV Community by Ali Shahriari (MasterPars) (@masterpars).</description>
    <link>https://dev.to/masterpars</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2108353%2F5920adf4-5fdf-40ba-a4b9-3bd1b79988fe.jpg</url>
      <title>DEV Community: Ali Shahriari (MasterPars)</title>
      <link>https://dev.to/masterpars</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/masterpars"/>
    <language>en</language>
    <item>
      <title>Mastering EF Core Interceptors: A Practical Guide</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Mon, 03 Nov 2025 09:54:40 +0000</pubDate>
      <link>https://dev.to/masterpars/mastering-ef-core-interceptors-a-practical-guide-5f6e</link>
      <guid>https://dev.to/masterpars/mastering-ef-core-interceptors-a-practical-guide-5f6e</guid>
      <description>&lt;p&gt;Entity Framework Core Interceptors are one of the most powerful yet underused features in EF Core. They allow you to hook into EF's pipeline and execute custom logic whenever EF performs certain operations — such as executing queries, saving data, or connecting to the database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In this article, we'll explore:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;✅ What EF Core Interceptors are&lt;/li&gt;
&lt;li&gt;✅ When you should use them&lt;/li&gt;
&lt;li&gt;✅ Real production-ready examples&lt;/li&gt;
&lt;li&gt;✅ Audit &amp;amp; Soft Delete implementations&lt;/li&gt;
&lt;li&gt;✅ Logging SQL queries
Let's dive in and see how EF Interceptors level up your application!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;🔥 Why Use EF Core Interceptors?&lt;/strong&gt;&lt;br&gt;
EF Core Interceptors help you:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Automatically modify database operations&lt;/li&gt;
&lt;li&gt;Track changes without touching business logic&lt;/li&gt;
&lt;li&gt;Enforce global rules&lt;/li&gt;
&lt;li&gt;Log SQL queries&lt;/li&gt;
&lt;li&gt;Apply cross‑cutting concerns (audit, soft delete, multi‑tenancy)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;They're like ASP.NET middleware — but for EF Core.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;🧠 Types of Interceptors in EF Core&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;IDbCommandInterceptor&lt;/code&gt;       =&amp;gt; Log or modify SQL commands&lt;br&gt;
&lt;code&gt;ISaveChangesInterceptor&lt;/code&gt;      =&amp;gt; Audit, Soft Delete, Validation&lt;br&gt;
&lt;code&gt;IConnectionInterceptor&lt;/code&gt;      =&amp;gt; Track DB connectivity events&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;✅ SQL Logging Interceptor Example&lt;/strong&gt;&lt;br&gt;
Logs SQL commands executed by EF Core (useful for debugging &amp;amp; production observability)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.EntityFrameworkCore.Diagnostics;
using System.Data.Common;
using Microsoft.Extensions.Logging;


public class SqlLoggingInterceptor : DbCommandInterceptor
{
    private readonly ILogger&amp;lt;SqlLoggingInterceptor&amp;gt; _logger;


    public SqlLoggingInterceptor(ILogger&amp;lt;SqlLoggingInterceptor&amp;gt; logger)
    {
     _logger = logger;
    }


    public override InterceptionResult&amp;lt;DbDataReader&amp;gt; ReaderExecuting(
    DbCommand command,
    CommandEventData eventData,
    InterceptionResult&amp;lt;DbDataReader&amp;gt; result)
    {
     _logger.LogInformation("EF SQL: {Sql}", command.CommandText);
     return base.ReaderExecuting(command, eventData, result);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ Register in Program.cs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddDbContext&amp;lt;AppDbContext&amp;gt;((sp, options) =&amp;gt;
 {
options.UseSqlServer(builder.Configuration.GetConnectionString("Default"));
options.AddInterceptors(sp.GetRequiredService&amp;lt;SqlLoggingInterceptor&amp;gt;());
});


builder.Services.AddScoped&amp;lt;SqlLoggingInterceptor&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;✅ Soft Delete Interceptor&lt;/strong&gt;&lt;br&gt;
Instead of removing row → mark as deleted.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Soft‑Delete Entity Base Class&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public abstract class SoftDeletableEntity
{
    public bool IsDeleted { get; set; }
    public DateTime? DeletedAt { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;User Provider&lt;/strong&gt;&lt;br&gt;
We need a service to get the current authenticated user:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ICurrentUserService
{
string? GetUserId();
}


public class HttpCurrentUserService : ICurrentUserService
{
private readonly IHttpContextAccessor _context;
public HttpCurrentUserService(IHttpContextAccessor context) =&amp;gt; _context = context;


public string? GetUserId()
=&amp;gt; _context.HttpContext?.User?.FindFirst("sub")?.Value // JWT `sub`
?? _context.HttpContext?.User?.Identity?.Name;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Interceptor (Audit + User)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;


public class SoftDeleteInterceptor : SaveChangesInterceptor
{
public override ValueTask&amp;lt;InterceptionResult&amp;lt;int&amp;gt;&amp;gt; SavingChangesAsync(
DbContextEventData eventData,
InterceptionResult&amp;lt;int&amp;gt; result,
CancellationToken cancellationToken = default)
{
var context = eventData.Context;


foreach (var entry in context.ChangeTracker.Entries&amp;lt;SoftDeletableEntity&amp;gt;())
{
if (entry.State == EntityState.Deleted)
{
entry.State = EntityState.Modified;
entry.Entity.IsDeleted = true;
entry.Entity.DeletedAt = DateTime.UtcNow;
}
}


return base.SavingChangesAsync(eventData, result, cancellationToken);
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Global Query Filter&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity&amp;lt;Post&amp;gt;().HasQueryFilter(x =&amp;gt; !x.IsDeleted);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;✅ Advanced Audit Interceptor (CreatedAt, UpdatedAt, UserId)&lt;/strong&gt;&lt;br&gt;
Tracking who created and updated records is essential in enterprise systems. With EF Core Interceptors, you can automatically populate:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;CreatedAt&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;UpdatedAt&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;UserId&lt;/code&gt; (current authenticated user)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Automatically fill audit fields.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Base Entity (Auditable)&lt;/strong&gt;&lt;br&gt;
We extend the base entity to include &lt;code&gt;UserId&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public abstract class AuditableEntity
{
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public string UserId { get; set; } // Creator / last modifier
}
{
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Interceptor&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class AuditInterceptor : SaveChangesInterceptor
{
private readonly ICurrentUserService _currentUser;
public AuditInterceptor(ICurrentUserService currentUser) =&amp;gt; _currentUser = currentUser;


public override ValueTask&amp;lt;InterceptionResult&amp;lt;int&amp;gt;&amp;gt; SavingChangesAsync(
DbContextEventData eventData,
InterceptionResult&amp;lt;int&amp;gt; result,
CancellationToken cancellationToken = default)
{
var context = eventData.Context;
var utcNow = DateTime.UtcNow;
var userId = _currentUser.GetUserId() ?? "system";


foreach (var entry in context.ChangeTracker.Entries&amp;lt;AuditableEntity&amp;gt;())
{
if (entry.State == EntityState.Added)
{
entry.Entity.CreatedAt = utcNow;
entry.Entity.UpdatedAt = utcNow;
entry.Entity.UserId = userId;
}
else if (entry.State == EntityState.Modified)
{
entry.Property(x =&amp;gt; x.CreatedAt).IsModified = false;
entry.Property(x =&amp;gt; x.UserId).IsModified = false;
entry.Entity.UpdatedAt = utcNow;
entry.Entity.UserId = userId;
}
}


return base.SavingChangesAsync(eventData, result, cancellationToken);
}
} : SaveChangesInterceptor
{
public override ValueTask&amp;lt;InterceptionResult&amp;lt;int&amp;gt;&amp;gt; SavingChangesAsync(
DbContextEventData eventData,
InterceptionResult&amp;lt;int&amp;gt; result,
CancellationToken cancellationToken = default)
{
var context = eventData.Context;
var utcNow = DateTime.UtcNow;


foreach (var entry in context.ChangeTracker.Entries&amp;lt;AuditableEntity&amp;gt;())
{
if (entry.State == EntityState.Added)
{
entry.Entity.CreatedAt = utcNow;
entry.Entity.UpdatedAt = utcNow;
}
else if (entry.State == EntityState.Modified)
{
entry.Property(x =&amp;gt; x.CreatedAt).IsModified = false;
entry.Entity.UpdatedAt = utcNow;
}
}


return base.SavingChangesAsync(eventData, result, cancellationToken);
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Register Interceptors&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddScoped&amp;lt;SoftDeleteInterceptor&amp;gt;();
builder.Services.AddScoped&amp;lt;AuditInterceptor&amp;gt;();


builder.Services.AddDbContext&amp;lt;AppDbContext&amp;gt;((sp, options) =&amp;gt;
{
options.UseSqlServer(builder.Configuration.GetConnectionString("Default"));
options.AddInterceptors(
sp.GetRequiredService&amp;lt;SoftDeleteInterceptor&amp;gt;(),
sp.GetRequiredService&amp;lt;AuditInterceptor&amp;gt;()
);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;🎯 Final Thoughts&lt;/strong&gt;&lt;br&gt;
EF Core Interceptors let you apply enterprise‑grade data rules without scattering logic across your application.&lt;br&gt;
Use them for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Logging SQL&lt;/li&gt;
&lt;li&gt;Audit metadata&lt;/li&gt;
&lt;li&gt;Soft delete&lt;/li&gt;
&lt;li&gt;Multi‑tenancy&lt;/li&gt;
&lt;li&gt;Security rules
If you're building serious systems — start using interceptors today.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>interceptors</category>
      <category>efcore</category>
      <category>csharp</category>
    </item>
    <item>
      <title>🚀 Improving Performance with Cursor Pagination in EF Core</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Mon, 14 Jul 2025 08:40:32 +0000</pubDate>
      <link>https://dev.to/masterpars/improving-performance-with-cursor-pagination-in-ef-core-5333</link>
      <guid>https://dev.to/masterpars/improving-performance-with-cursor-pagination-in-ef-core-5333</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;🧠 Why Pagination Matters&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In modern applications, especially dashboards and APIs with potentially large datasets (think millions of records), effective pagination isn't just a UI concern — it's a &lt;strong&gt;performance-critical backend feature&lt;/strong&gt;. Poor pagination techniques can cause memory pressure, increased latency, and even database timeouts.&lt;/p&gt;

&lt;p&gt;While &lt;strong&gt;Offset-based pagination&lt;/strong&gt; (using &lt;code&gt;Skip()&lt;/code&gt; and &lt;code&gt;Take()&lt;/code&gt;) is the go-to solution, it's far from efficient at scale. This is where Cursor Pagination comes in.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;⛔️ The Problem with Offset Pagination&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Let's consider this classic example using EF Core:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var page = 1000;
var pageSize = 20;
var result = db.Posts
    .OrderBy(p =&amp;gt; p.CreatedAt)
    .Skip(page * pageSize)
    .Take(pageSize)
    .ToList();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Here’s why this is a performance killer:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Skip is costly&lt;/strong&gt;: SQL Server still reads through the previous 20,000 rows.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Inconsistent results&lt;/strong&gt;: New inserts or deletes between pages cause missing or duplicate data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Index inefficiency&lt;/strong&gt;: Even if &lt;code&gt;CreatedAt&lt;/code&gt; is indexed, &lt;code&gt;Skip&lt;/code&gt; breaks the seek pattern.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;✅ Enter Cursor Pagination&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Cursor pagination uses a stable reference (like a timestamp or ID) instead of offsets. You only fetch rows &lt;strong&gt;after or before&lt;/strong&gt; a known record.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var pageSize = 20;
var cursor = lastSeenCreatedAt; // usually from client

var result = db.Posts
    .Where(p =&amp;gt; p.CreatedAt &amp;gt; cursor)
    .OrderBy(p =&amp;gt; p.CreatedAt)
    .Take(pageSize)
    .ToList();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, instead of scanning from the beginning, EF Core (and ultimately SQL Server) jumps &lt;strong&gt;directly&lt;/strong&gt; to the cursor point using an index seek.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🔬 Real Benchmark: Offset vs Cursor&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;I benchmarked both strategies over a table with &lt;strong&gt;1,000,000&lt;/strong&gt; records using EF Core 8 + SQL Server 2022. Here’s what I found when paginating to record ~page 1000 (offset 20,000):&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Strategy&lt;/th&gt;
&lt;th&gt;Query Time (ms)&lt;/th&gt;
&lt;th&gt;CPU (%)&lt;/th&gt;
&lt;th&gt;Memory (MB)&lt;/th&gt;
&lt;th&gt;IO Reads&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Offset Pagination&lt;/td&gt;
&lt;td&gt;420ms&lt;/td&gt;
&lt;td&gt;38%&lt;/td&gt;
&lt;td&gt;102MB&lt;/td&gt;
&lt;td&gt;High&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cursor Pagination&lt;/td&gt;
&lt;td&gt;12ms&lt;/td&gt;
&lt;td&gt;2%&lt;/td&gt;
&lt;td&gt;7MB&lt;/td&gt;
&lt;td&gt;Very Low&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;⚠ Offset pagination consumed &lt;strong&gt;10x more CPU and 14x more memory&lt;/strong&gt;, while delivering the same data.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;💡 Tips for Using Cursor Pagination in EF Core&lt;/strong&gt;
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Use indexed columns&lt;/strong&gt; as cursor anchors (e.g., &lt;code&gt;CreatedAt&lt;/code&gt;, &lt;code&gt;Id&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Order consistently&lt;/strong&gt; — always use &lt;code&gt;OrderBy&lt;/code&gt; on the cursor column.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use composite cursors&lt;/strong&gt; if needed: e.g., &lt;code&gt;CreatedAt&lt;/code&gt; + &lt;code&gt;Id&lt;/code&gt;to ensure uniqueness.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Base64-encode cursor values&lt;/strong&gt; for API endpoints to keep URLs clean.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🧪 Sample API Implementation (Minimal API)&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.MapGet("/posts", async (DateTime? after, AppDbContext db) =&amp;gt;
{
    var query = db.Posts.AsQueryable();

    if (after.HasValue)
        query = query.Where(p =&amp;gt; p.CreatedAt &amp;gt; after.Value);

    var results = await query
        .OrderBy(p =&amp;gt; p.CreatedAt)
        .Take(20)
        .ToListAsync();

    return Results.Ok(results);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;✨ When NOT to Use Cursor Pagination&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;When strict page numbers are needed (e.g., jumping to page 500).&lt;/li&gt;
&lt;li&gt;When sorting by non-unique or non-indexed fields.&lt;/li&gt;
&lt;li&gt;For static datasets that rarely change.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🚀 TL;DR&lt;/strong&gt;
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Pagination Type&lt;/th&gt;
&lt;th&gt;Performance&lt;/th&gt;
&lt;th&gt;Stable Ordering&lt;/th&gt;
&lt;th&gt;Suitable for APIs&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Offset Pagination&lt;/td&gt;
&lt;td&gt;❌ Poor&lt;/td&gt;
&lt;td&gt;❌ No&lt;/td&gt;
&lt;td&gt;✅ Basic cases&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cursor Pagination&lt;/td&gt;
&lt;td&gt;✅ Great&lt;/td&gt;
&lt;td&gt;✅ Yes&lt;/td&gt;
&lt;td&gt;✅ Highly recommended&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;💬 Final Thoughts&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Cursor pagination is a powerful tool in the hands of performance-conscious developers. With minimal refactoring, you can &lt;strong&gt;greatly improve data access speed, scalability, and UX&lt;/strong&gt;. As always, profile your queries — every millisecond counts.&lt;/p&gt;

</description>
      <category>efcore</category>
      <category>performance</category>
      <category>dotnet</category>
      <category>pagination</category>
    </item>
    <item>
      <title>Understanding the Decorator Pattern Through a MacBook Customization Example in C#</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Tue, 10 Jun 2025 07:48:28 +0000</pubDate>
      <link>https://dev.to/masterpars/understanding-the-decorator-pattern-through-a-macbook-customization-example-in-c-6jj</link>
      <guid>https://dev.to/masterpars/understanding-the-decorator-pattern-through-a-macbook-customization-example-in-c-6jj</guid>
      <description>&lt;p&gt;The &lt;code&gt;Decorator Pattern&lt;/code&gt; is a powerful structural design pattern that enables adding new behavior to objects dynamically without modifying their original code. This is especially useful when you want to extend functionalities without creating a complex hierarchy of subclasses.&lt;/p&gt;

&lt;p&gt;In this article, I’ll explain the Decorator Pattern using a practical example: customizing a MacBook with different configurations like upgrading RAM, SSD, and adding AppleCare protection.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;What is the Decorator Pattern?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Decorator Pattern allows you to "wrap" an object with additional features or responsibilities at runtime. Instead of creating many subclasses for every possible combination, decorators let you compose behaviors dynamically by stacking objects.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;The MacBook Example Overview&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;We start with a base MacBook configuration:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;16GB RAM&lt;/li&gt;
&lt;li&gt;256GB SSD&lt;/li&gt;
&lt;li&gt;Base price&lt;/li&gt;
&lt;li&gt;Using decorators, we can:&lt;/li&gt;
&lt;li&gt;Upgrade RAM to 24GB&lt;/li&gt;
&lt;li&gt;Upgrade SSD to 512GB&lt;/li&gt;
&lt;li&gt;Add AppleCare protection&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each decorator modifies the price and relevant specs accordingly.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Core Components&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The Interface &lt;code&gt;IMacBook&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Defines the contract with methods like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;GetDescription()&lt;/li&gt;
&lt;li&gt;GetPrice()&lt;/li&gt;
&lt;li&gt;GetRamSize()&lt;/li&gt;
&lt;li&gt;GetSSDSize()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The Base Class &lt;code&gt;BaseMacBook16Ram256SSD&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implements &lt;code&gt;IMacBook&lt;/code&gt; and represents the default MacBook configuration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Abstract Decorator &lt;code&gt;MackBookDecorator&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This class implements &lt;code&gt;IMacBook&lt;/code&gt; and wraps another &lt;code&gt;IMacBook&lt;/code&gt; instance. It delegates calls to the wrapped instance but can be extended to add or override behavior.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Concrete Decorators&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;MacBookWithAppleCare&lt;/code&gt;: Adds AppleCare price and description.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;MacBook512SSD&lt;/code&gt;: Adds extra SSD storage and price.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;MacBook24RAM&lt;/code&gt;: Adds extra RAM and price.&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;
  
  
  &lt;strong&gt;How to Use It&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;You can compose different MacBook configurations by wrapping the base object with decorators like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;IMacBook macBook16Ram256SSD = new BaseMacBook16Ram256SSD();
IMacBook macBook16Ram512Sdd = new MacBook512SSD(macBook16Ram256SSD);
IMacBook macBook24Ram512Sdd = new MacBook24RAM(macBook16Ram512Sdd);
IMacBook macBook24Ram512SddWithAppleCare = new MacBookWithAppleCare(macBook24Ram512Sdd);

Console.WriteLine(macBook16Ram256SSD);
Console.WriteLine(macBook16Ram512Sdd);
Console.WriteLine(macBook24Ram512Sdd);
Console.WriteLine(macBook24Ram512SddWithAppleCare);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each line creates a new configuration by decorating the previous one.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Why Use the Decorator Pattern?&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Open/Closed Principle:&lt;/strong&gt; Extend object behavior without changing existing code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Flexibility:&lt;/strong&gt; Combine decorators in any order to create new behaviors.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Avoids Class Explosion:&lt;/strong&gt; No need to create a subclass for every combination.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Real-World Applications&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Decorator Pattern is widely used in software development:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Adding scrollbars or borders in UI frameworks.&lt;/li&gt;
&lt;li&gt;Enhancing functionalities like logging, caching, or security by wrapping services.&lt;/li&gt;
&lt;li&gt;Customizing product configurations dynamically, just like our MacBook example.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Decorator Pattern is an elegant way to add responsibilities to objects dynamically and flexibly. Using this pattern, you keep your codebase maintainable and avoid unnecessary class proliferation.&lt;/p&gt;




&lt;p&gt;You can find the full source code for this example on my GitHub repository: &lt;a href="https://github.com/MasterPars-2018/DecoratorPattern" rel="noopener noreferrer"&gt;DecoratorPattern&lt;/a&gt;  &lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>designpatterns</category>
      <category>decorator</category>
      <category>solidprinciples</category>
    </item>
    <item>
      <title>Observer Pattern Explained: How It Helps Build Flexible and Scalable Systems</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Sun, 01 Jun 2025 06:30:42 +0000</pubDate>
      <link>https://dev.to/masterpars/observer-pattern-explained-how-it-helps-build-flexible-and-scalable-systems-5ec</link>
      <guid>https://dev.to/masterpars/observer-pattern-explained-how-it-helps-build-flexible-and-scalable-systems-5ec</guid>
      <description>&lt;p&gt;Design patterns are proven solutions to common software design problems. Among them, the Observer Pattern stands out as a powerful tool for managing communication between objects in a loosely coupled way.&lt;/p&gt;

&lt;p&gt;In this article, we'll explore the &lt;strong&gt;Observer Pattern&lt;/strong&gt; in depth and use a simple but effective example — a smart home temperature monitoring system — to demonstrate why this pattern is so useful.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;What is the Observer Pattern?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;Observer Pattern&lt;/strong&gt; defines a one-to-many relationship between objects: one &lt;strong&gt;subject&lt;/strong&gt; (also called observable) maintains a list of its dependents, called observers, and automatically notifies them of any state changes, usually by calling one of their methods.&lt;/p&gt;

&lt;p&gt;This pattern is especially helpful when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You want to decouple objects so that changes in one object are automatically reflected in others without tight integration.&lt;/li&gt;
&lt;li&gt;You need dynamic subscription, where observers can be added or removed at runtime.&lt;/li&gt;
&lt;li&gt;You want to implement event-driven or reactive systems cleanly.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Key Components of Observer Pattern&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Subject (Observable)&lt;/strong&gt;: The object that holds the data or state and notifies observers about changes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Observers&lt;/strong&gt;: The objects that want to be informed about changes in the subject.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Registration Methods&lt;/strong&gt;: Observers can subscribe or unsubscribe to the subject’s notifications.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Notification Method&lt;/strong&gt;: The subject notifies all registered observers about state changes.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Why Use Observer Pattern?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Consider a system where many parts need to react to changes in a central data source. Without this pattern, you might end up with:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Tight coupling&lt;/strong&gt;: Each dependent object needs explicit knowledge of others.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Complex code&lt;/strong&gt;: Manual updates, hard-coded logic, and difficulty in maintenance.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Limited flexibility&lt;/strong&gt;: Adding/removing observers requires changing core logic.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Observer Pattern solves these issues by promoting loose coupling and separation of concerns.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;A Practical Example: Smart Home Temperature Monitoring&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Let's imagine a &lt;strong&gt;smart home system&lt;/strong&gt; where &lt;strong&gt;a Temperature Sensor&lt;/strong&gt; monitors the current temperature. Multiple devices depend on this information:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Thermostat&lt;/strong&gt;: Adjusts heating or cooling based on temperature.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Smart Window&lt;/strong&gt;: Opens or closes depending on how hot or cold it is.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Notification System&lt;/strong&gt;: Sends alerts if temperature goes outside safe limits.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;How Observer Pattern Fits Here&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Temperature Sensor is the &lt;strong&gt;Subject&lt;/strong&gt;. It holds the temperature state and notifies all registered observers when the temperature changes.&lt;/p&gt;

&lt;p&gt;Each device implements an &lt;strong&gt;Observer&lt;/strong&gt; interface with an update method that the sensor calls whenever the temperature changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This means&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The sensor doesn’t need to know details about devices.&lt;/li&gt;
&lt;li&gt;Devices can be added or removed without modifying the sensor.&lt;/li&gt;
&lt;li&gt;The system is extendable and maintainable.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Code Walkthrough (C#)&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Observer Interface
public interface IObserver
{
    void Update(float temperature);
}

// Subject Interface
public interface ISubject
{
    void RegisterObserver(IObserver observer);
    void RemoveObserver(IObserver observer);
    void NotifyObservers();
}

// Concrete Subject
public class TemperatureSensor : ISubject
{
    private List&amp;lt;IObserver&amp;gt; observers = new List&amp;lt;IObserver&amp;gt;();
    private float temperature;

    public void RegisterObserver(IObserver observer) =&amp;gt; observers.Add(observer);
    public void RemoveObserver(IObserver observer) =&amp;gt; observers.Remove(observer);

    public void NotifyObservers()
    {
        foreach (var observer in observers)
        {
            observer.Update(temperature);
        }
    }

    public void SetTemperature(float newTemperature)
    {
        temperature = newTemperature;
        NotifyObservers();
    }
}

// Concrete Observers
public class Thermostat : IObserver
{
    public void Update(float temperature)
    {
        if (temperature &amp;lt; 20)
            Console.WriteLine("Thermostat: Heating ON.");
        else if (temperature &amp;gt; 25)
            Console.WriteLine("Thermostat: Cooling ON.");
        else
            Console.WriteLine("Thermostat: System OFF.");
    }
}

public class SmartWindow : IObserver
{
    public void Update(float temperature)
    {
        if (temperature &amp;gt; 27)
            Console.WriteLine("SmartWindow: Opening window.");
        else
            Console.WriteLine("SmartWindow: Closing window.");
    }
}

public class NotificationSystem : IObserver
{
    public void Update(float temperature)
    {
        if (temperature &amp;gt; 30 || temperature &amp;lt; 10)
            Console.WriteLine("Notification: Temperature out of safe range!");
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;Benefits of Using Observer Pattern&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Loose Coupling&lt;/strong&gt;: The subject and observers interact via interfaces, reducing dependencies.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Extensibility&lt;/strong&gt;: Adding new observers requires no change to the subject.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dynamic Subscription&lt;/strong&gt;: Observers can register/unregister at runtime.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Improved Maintainability&lt;/strong&gt;: Separation of concerns makes the system easier to manage.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;When to Use the Observer Pattern?&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;You have an object whose state changes and many other objects need to react to these changes.&lt;/li&gt;
&lt;li&gt;You want to avoid tight coupling between objects.&lt;/li&gt;
&lt;li&gt;You need a scalable, event-driven architecture.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Observer Pattern is a powerful and flexible design pattern that helps you build scalable, maintainable software. Using the smart home temperature monitoring example, we see how a subject (temperature sensor) can notify multiple observers (devices) efficiently and cleanly.&lt;/p&gt;

&lt;p&gt;By applying this pattern, you make your code easier to extend, test, and maintain — essential qualities for any real-world software system.&lt;/p&gt;

</description>
      <category>observerpattern</category>
      <category>programming</category>
      <category>designpatterns</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>🎯 A Clean Way to Inject Strategy Pattern in C# Using Factory and DI Dictionary</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Tue, 27 May 2025 06:20:49 +0000</pubDate>
      <link>https://dev.to/masterpars/a-clean-way-to-inject-strategy-pattern-in-c-using-factory-and-di-dictionary-2716</link>
      <guid>https://dev.to/masterpars/a-clean-way-to-inject-strategy-pattern-in-c-using-factory-and-di-dictionary-2716</guid>
      <description>&lt;p&gt;When implementing multiple behaviors like discount strategies, the common trap is hardcoding logic into service classes or bloating factories with &lt;code&gt;switch&lt;/code&gt;statements. Let’s explore a cleaner, extensible way using:&lt;/p&gt;

&lt;p&gt;✅ Strategy Pattern&lt;br&gt;
✅ Factory Pattern&lt;br&gt;
✅ Dependency Injection via &lt;code&gt;Dictionary&amp;lt;Enum, Func&amp;lt;T&amp;gt;&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This approach is minimal, testable, and elegant—especially if you want to add more strategies later with zero friction.&lt;/p&gt;


&lt;h2&gt;
  
  
  &lt;strong&gt;🧠 The Scenario&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Suppose you're building an e-commerce platform that supports various discount types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Percentage-based discount (e.g., 20% off)&lt;/li&gt;
&lt;li&gt;Fixed amount discount (e.g., $10 off)&lt;/li&gt;
&lt;li&gt;Buy One Get One Free (BOGO)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each of these follows different logic, but they all return the final price.&lt;/p&gt;


&lt;h2&gt;
  
  
  &lt;strong&gt;🧱 Step 1: Define the Strategy Interface&lt;/strong&gt;
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IDiscountStrategy
{
    decimal ApplyDiscount(decimal unitPrice, int quantity);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;🛠 Step 2: Implement Each Strategy&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;PercentageDiscount:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class PercentageDiscount : IDiscountStrategy
{
    private readonly decimal _percentage = 0.2m;

    public decimal ApplyDiscount(decimal unitPrice, int quantity)
    {
        var total = unitPrice * quantity;
        return total - (total * _percentage);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;FixedAmountDiscount:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class FixedAmountDiscount : IDiscountStrategy
{
    private readonly decimal _amount = 10m;

    public decimal ApplyDiscount(decimal unitPrice, int quantity)
    {
        var total = unitPrice * quantity;
        return total - _amount;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;BuyOneGetOneDiscount:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class BuyOneGetOneDiscount : IDiscountStrategy
{
    public decimal ApplyDiscount(decimal unitPrice, int quantity)
    {
        var payableQuantity = (quantity / 2) + (quantity % 2);
        return unitPrice * payableQuantity;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🏭 Step 4: Implement the Factory&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Instead of injecting &lt;code&gt;IServiceProvider&lt;/code&gt;, we inject a dictionary of factory functions. This keeps your factory clean and &lt;strong&gt;testable&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IDiscountFactory:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IDiscountFactory
{
    IDiscountStrategy GetStrategy(DiscountType type);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;DiscountFactory (with DI Dictionary)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DiscountFactory : IDiscountFactory
{
    private readonly IReadOnlyDictionary&amp;lt;DiscountType, Func&amp;lt;IDiscountStrategy&amp;gt;&amp;gt; _strategyResolvers;

    public DiscountFactory(IReadOnlyDictionary&amp;lt;DiscountType, Func&amp;lt;IDiscountStrategy&amp;gt;&amp;gt; strategyResolvers)
    {
        _strategyResolvers = strategyResolvers;
    }

    public IDiscountStrategy GetStrategy(DiscountType type)
    {
        if (_strategyResolvers.TryGetValue(type, out var resolver))
        {
            return resolver();
        }

        throw new ArgumentOutOfRangeException(nameof(type), $"Unsupported discount type: {type}");
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;💼 Step 5: Define the Purchase Service Interface&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IPurchaseService
{
    decimal CalculateFinalPrice(decimal unitPrice, int quantity, DiscountType discountType);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;💳 Step 6: Implement PurchaseService Using the Factory&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class PurchaseService : IPurchaseService
{
    private readonly IDiscountFactory _discountFactory;

    public PurchaseService(IDiscountFactory discountFactory)
    {
        _discountFactory = discountFactory;
    }

    public decimal CalculateFinalPrice(decimal unitPrice, int quantity, DiscountType discountType)
    {
        var strategy = _discountFactory.GetStrategy(discountType);
        return strategy.ApplyDiscount(unitPrice, quantity);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🧩 Step 7: Register Everything in Program.cs&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped&amp;lt;PercentageDiscount&amp;gt;();
builder.Services.AddScoped&amp;lt;FixedAmountDiscount&amp;gt;();
builder.Services.AddScoped&amp;lt;BuyOneGetOneDiscount&amp;gt;();

builder.Services.AddScoped&amp;lt;IReadOnlyDictionary&amp;lt;DiscountType, Func&amp;lt;IDiscountStrategy&amp;gt;&amp;gt;&amp;gt;(sp =&amp;gt;
    new Dictionary&amp;lt;DiscountType, Func&amp;lt;IDiscountStrategy&amp;gt;&amp;gt;
    {
        [DiscountType.Percentage] = () =&amp;gt; sp.GetRequiredService&amp;lt;PercentageDiscount&amp;gt;(),
        [DiscountType.FixedAmount] = () =&amp;gt; sp.GetRequiredService&amp;lt;FixedAmountDiscount&amp;gt;(),
        [DiscountType.BuyOneGetOne] = () =&amp;gt; sp.GetRequiredService&amp;lt;BuyOneGetOneDiscount&amp;gt;()
    });

builder.Services.AddScoped&amp;lt;IDiscountFactory, DiscountFactory&amp;gt;();
builder.Services.AddScoped&amp;lt;IPurchaseService, PurchaseService&amp;gt;();

var app = builder.Build();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🧪 Step 8: Real-World Usage (e.g., Controller or Console Output)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Let’s demonstrate this in &lt;code&gt;Program.cs&lt;/code&gt; using console output (ideal for early testing or debugging):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using var scope = app.Services.CreateScope();
var purchaseService = scope.ServiceProvider.GetRequiredService&amp;lt;IPurchaseService&amp;gt;();

Console.WriteLine("=== DISCOUNT CALCULATOR ===");

var price = purchaseService.CalculateFinalPrice(100m, 3, DiscountType.BuyOneGetOne);
Console.WriteLine($"Buy 3 items at $100 each with BOGO =&amp;gt; Final price: {price:C}");

price = purchaseService.CalculateFinalPrice(100m, 3, DiscountType.Percentage);
Console.WriteLine($"Buy 3 items at $100 each with 20% discount =&amp;gt; Final price: {price:C}");

price = purchaseService.CalculateFinalPrice(100m, 3, DiscountType.FixedAmount);
Console.WriteLine($"Buy 3 items at $100 each with $10 off =&amp;gt; Final price: {price:C}");

app.Run();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;✅ Final Thoughts&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;This architecture blends clean code, testability, and maintainability. You gain the flexibility to plug in new discount logic without touching the core business service or polluting the factory with conditionals.&lt;/p&gt;

&lt;p&gt;You can extend this pattern to other domains like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Shipping methods&lt;/li&gt;
&lt;li&gt;Tax strategies&lt;/li&gt;
&lt;li&gt;Report generators&lt;/li&gt;
&lt;li&gt;Notification channels&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>stratgy</category>
      <category>factory</category>
    </item>
    <item>
      <title>Building Resilient .NET 10 Applications with Polly</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Tue, 20 May 2025 03:47:08 +0000</pubDate>
      <link>https://dev.to/masterpars/building-resilient-net-10-applications-with-polly-4lck</link>
      <guid>https://dev.to/masterpars/building-resilient-net-10-applications-with-polly-4lck</guid>
      <description>&lt;p&gt;In modern distributed systems and microservices, failure is inevitable. Building resilient applications that can gracefully handle failures and recover quickly is critical. In .NET 10, Polly provides a powerful way to implement resilience patterns like Retry, Circuit Breaker, Timeout, and Fallback.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🚧 Why Resilience Matters&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Network instability&lt;/li&gt;
&lt;li&gt;Timeouts from external APIs&lt;/li&gt;
&lt;li&gt;Temporary unavailability of services&lt;/li&gt;
&lt;li&gt;Slow downstream services&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Without resilience strategies, your application may crash or degrade badly under such conditions.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🛠 Introduction to Polly&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Polly&lt;/strong&gt; is a .NET resilience and transient-fault-handling library that allows developers to express policies such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Retry&lt;/li&gt;
&lt;li&gt;Circuit Breaker&lt;/li&gt;
&lt;li&gt;Timeout&lt;/li&gt;
&lt;li&gt;Fallback&lt;/li&gt;
&lt;li&gt;Bulkhead Isolation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It works seamlessly with &lt;code&gt;HttpClientFactory&lt;/code&gt; and the new features in .NET 10.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🔁 Retry Policy&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Retries a failed operation a specified number of times before throwing an exception.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var retryPolicy = Policy
    .Handle&amp;lt;HttpRequestException&amp;gt;()
    .RetryAsync(3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;⚡ Circuit Breaker Policy&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Prevents your system from overwhelming failing services. Opens the circuit after a number of failures.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var circuitBreakerPolicy = Policy
    .Handle&amp;lt;HttpRequestException&amp;gt;()
    .CircuitBreakerAsync(
        handledEventsAllowedBeforeBreaking: 5,
        durationOfBreak: TimeSpan.FromSeconds(30));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;⏳ Timeout Policy&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Cancels requests that take longer than a specified time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var timeoutPolicy = Policy
    .TimeoutAsync&amp;lt;HttpResponseMessage&amp;gt;(5); // seconds
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🧰 Fallback Policy&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Provides a default value or alternative logic when a request fails.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var fallbackPolicy = Policy&amp;lt;HttpResponseMessage&amp;gt;
    .Handle&amp;lt;Exception&amp;gt;()
    .FallbackAsync(new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent("Fallback response")
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🧪 Combining Policies&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;You can chain multiple policies for more robust control.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var policyWrap = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy, timeoutPolicy);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🌐 Using Polly with HttpClientFactory in .NET 10&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddHttpClient("ResilientClient")
    .AddPolicyHandler(policyWrap);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;📌 Best Practices&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use policy logging for observability&lt;/li&gt;
&lt;li&gt;Avoid retrying non-transient faults&lt;/li&gt;
&lt;li&gt;Tune thresholds based on your system’s behavior&lt;/li&gt;
&lt;li&gt;Combine policies wisely to avoid over-complexity&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;✅ Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Resilience is not a luxury—it's a necessity in distributed applications. With &lt;code&gt;Polly&lt;/code&gt;and .NET 10, you can build applications that are robust, responsive, and reliable even in the face of failure. Start small, test often, and tune gradually to create truly resilient systems.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>polly</category>
      <category>programming</category>
    </item>
    <item>
      <title>New Features in EF Core 10</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Mon, 19 May 2025 14:32:53 +0000</pubDate>
      <link>https://dev.to/masterpars/new-features-in-ef-core-10-4lc3</link>
      <guid>https://dev.to/masterpars/new-features-in-ef-core-10-4lc3</guid>
      <description>&lt;p&gt;Entity Framework Core 10 (EF10) introduces several powerful features aimed at enhancing performance, flexibility, and integration capabilities with modern data systems. In this article, we will explore the key features introduced in EF Core 10 and how they can be leveraged to optimize application development.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🌐 Azure Cosmos DB for NoSQL&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;One of the major enhancements in EF10 is the improved support for Azure Cosmos DB for NoSQL, enabling efficient database operations and powerful new capabilities:&lt;/p&gt;

&lt;p&gt;1- &lt;strong&gt;Full-text search support:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Allows high-performance text search directly on Cosmos DB documents.&lt;/li&gt;
&lt;li&gt;Supports functions like &lt;code&gt;FullTextContains&lt;/code&gt;, &lt;code&gt;FullTextContainsAll&lt;/code&gt;, and &lt;code&gt;FullTextContainsAny&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var results = await context.Blogs.Where(x =&amp;gt; EF.Functions.FullTextContains(x.Content, "EF Core 10"))
                                .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2- &lt;strong&gt;Hybrid search with Vector Similarity:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;EF10 now supports &lt;strong&gt;Reciprocal Rank Fusion (RRF)&lt;/strong&gt;, combining vector similarity and full-text search for hybrid queries.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;float[] myVector = {0.1f, 0.2f, 0.3f};
var results = await context.Blogs.OrderBy(x =&amp;gt; EF.Functions.Rrf(
    EF.Functions.FullTextScore(x.Content, "database"),
    EF.Functions.VectorDistance(x.Vector, myVector)))
.Take(10)
.ToListAsync();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🔍 LINQ and SQL Translation Enhancements&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;EF Core 10 introduces native support for new LINQ operators introduced in .NET 10:&lt;/p&gt;

&lt;p&gt;1- &lt;strong&gt;&lt;code&gt;LeftJoin&lt;/code&gt; and &lt;code&gt;RightJoin&lt;/code&gt; Support:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Simplifies complex join queries in LINQ.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var query = context.Students
    .LeftJoin(context.Departments,
             student =&amp;gt; student.DepartmentID,
             department =&amp;gt; department.ID,
             (student, department) =&amp;gt; new
             {
                 student.FirstName,
                 student.LastName,
                 Department = department.Name ?? "[NONE]"
             });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;⚡ ExecuteUpdateAsync Enhancements&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;ExecuteUpdateAsync&lt;/code&gt; now supports regular, non-expression lambdas, simplifying update logic:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await context.Blogs.ExecuteUpdateAsync(s =&amp;gt;
{
    s.SetProperty(b =&amp;gt; b.Views, 100);
    s.SetProperty(b =&amp;gt; b.Name, "Updated Blog Name");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This change eliminates the complexity of building expression trees manually, making bulk updates more readable and maintainable.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;📌 Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;EF Core 10 brings substantial improvements to database interactions, LINQ translations, and Cosmos DB integration. These new capabilities not only streamline development but also enhance performance and scalability for modern applications. Developers leveraging EF10 can build more efficient, data-driven applications with less code and improved readability.&lt;/p&gt;

</description>
      <category>efcore10</category>
      <category>csharp</category>
      <category>programming</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Advanced C# Performance Tuning Techniques</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Mon, 19 May 2025 06:39:39 +0000</pubDate>
      <link>https://dev.to/masterpars/advanced-c-performance-tuning-techniques-22n7</link>
      <guid>https://dev.to/masterpars/advanced-c-performance-tuning-techniques-22n7</guid>
      <description>&lt;p&gt;Optimizing performance in C# applications is crucial for building high-performance and scalable software solutions. This article dives deep into advanced performance tuning techniques that every C# developer should know.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🚀 Garbage Collection (GC) Optimization&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The .NET runtime uses Garbage Collection (GC) to manage memory automatically. However, improper handling can lead to performance bottlenecks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practices:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1- &lt;strong&gt;Avoid Large Object Heap (LOH) fragmentation:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use &lt;code&gt;ArrayPool&amp;lt;T&amp;gt;&lt;/code&gt; for large arrays to minimize memory fragmentation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2- &lt;strong&gt;Minimize Boxing and Unboxing:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Avoid unnecessary conversions between value types and reference types.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3- &lt;strong&gt;Manual GC Control:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use  &lt;code&gt;GC.Collect()&lt;/code&gt;  cautiously to force garbage collection when you know there is a memory spike.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Avoid manual GC.Collect() unless absolutely necessary
GC.Collect(); // Forces garbage collection - use with caution
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;⚡ Efficient Memory Management&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Memory management is crucial for high-performance applications. Techniques such as pooling, spans, and stack allocation can significantly improve memory usage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Techniques:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1- &lt;strong&gt;Object Pooling:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reuse objects instead of creating new instances. This is particularly effective for expensive-to-create objects.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2- &lt;strong&gt;Span and Memory:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use &lt;code&gt;Span&amp;lt;T&amp;gt;&lt;/code&gt; for stack-allocated memory to avoid heap allocation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Span&amp;lt;int&amp;gt; numbers = stackalloc int[5] { 1, 2, 3, 4, 5 };

foreach (var number in numbers)
{
    Console.WriteLine(number);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3- &lt;strong&gt;Avoiding Finalizers:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Classes with finalizers (~ClassName) are slower to collect. Avoid them when possible.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🔄 Asynchronous Programming Optimization&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Asynchronous operations can greatly improve performance if used correctly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Techniques:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1- &lt;strong&gt;Use ConfigureAwait(false):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Prevents unnecessary context switching, speeding up asynchronous calls.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2- &lt;strong&gt;Avoid Async Void:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use async Task instead of async void to enable proper error handling.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3- &lt;strong&gt;Task.WhenAll:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Run multiple tasks concurrently to speed up operations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await Task.WhenAll(Task1(), Task2(), Task3());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🔍 LINQ Optimization&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;LINQ is powerful but can be inefficient if not optimized.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Techniques:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1- &lt;strong&gt;Avoid Multiple Enumerations:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Do not iterate over the same LINQ query multiple times.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2- &lt;strong&gt;Use &lt;code&gt;.ToList()&lt;/code&gt; or &lt;code&gt;.ToArray()&lt;/code&gt; wisely:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Prevent multiple database calls by materializing the query results once.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3- &lt;strong&gt;Filter Early:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Apply &lt;code&gt;.Where()&lt;/code&gt; before &lt;code&gt;.Select()&lt;/code&gt; to minimize processing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var filteredData = data.Where(d =&amp;gt; d.IsActive).Select(d =&amp;gt; d.Name).ToList();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;📌 Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Mastering advanced performance tuning techniques in C# helps in building efficient, scalable, and maintainable applications. By understanding memory management, garbage collection, asynchronous operations, and LINQ optimization, developers can significantly improve the performance of their software.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>csharp</category>
      <category>dotnet</category>
      <category>performance</category>
    </item>
    <item>
      <title>Understanding the Key Differences Between IQueryable and IEnumerable</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Sun, 18 May 2025 07:29:09 +0000</pubDate>
      <link>https://dev.to/masterpars/understanding-the-key-differences-between-iqueryable-and-ienumerable-1np8</link>
      <guid>https://dev.to/masterpars/understanding-the-key-differences-between-iqueryable-and-ienumerable-1np8</guid>
      <description>&lt;p&gt;In the world of .NET development, understanding the differences between &lt;strong&gt;&lt;em&gt;IQueryable&lt;/em&gt;&lt;/strong&gt; and &lt;em&gt;&lt;strong&gt;IEnumerable&lt;/strong&gt;&lt;/em&gt; is crucial for optimizing application performance and ensuring efficient data querying. In this article, we will explore the fundamental differences, their use cases, and best practices for leveraging each interface effectively.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🔍 What is IEnumerable?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;IEnumerable&lt;/strong&gt; is an interface that allows you to iterate over a collection of objects. It is defined in the &lt;strong&gt;System.Collections&lt;/strong&gt; namespace and works best with in-memory data collections like lists or arrays.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Characteristics:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1- &lt;strong&gt;In-memory Processing:&lt;/strong&gt; All operations with IEnumerable are performed in memory.&lt;/p&gt;

&lt;p&gt;2- &lt;strong&gt;Deferred Execution:&lt;/strong&gt; It supports deferred execution, meaning the query is only executed when you iterate over it (e.g., with foreach).&lt;/p&gt;

&lt;p&gt;3- &lt;strong&gt;Client-side Filtering:&lt;/strong&gt; All filtering operations (Where, Select, etc.) are performed on the client side after the data is loaded into memory.&lt;/p&gt;

&lt;p&gt;4- &lt;strong&gt;Single Direction Iteration:&lt;/strong&gt; It only supports forward iteration over the collection.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;int&amp;gt; numbers = new List&amp;lt;int&amp;gt; { 1, 2, 3, 4, 5 };
IEnumerable&amp;lt;int&amp;gt; evenNumbers = numbers.Where(x =&amp;gt; x % 2 == 0);

// Iterating over the collection
foreach (var number in evenNumbers)
{
    Console.WriteLine(number);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;🔄 What is IQueryable?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;IQueryable&lt;/strong&gt; is an interface that allows LINQ-to-SQL queries to be translated and executed on a database server. It is defined in the &lt;strong&gt;System.Linq&lt;/strong&gt; namespace and is best used for querying data from a database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Characteristics:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1- &lt;strong&gt;Remote Query Execution:&lt;/strong&gt; Queries are executed on the database server, not in memory.&lt;/p&gt;

&lt;p&gt;2- &lt;strong&gt;Deferred Execution:&lt;/strong&gt; Similar to IEnumerable, execution is deferred until you enumerate over it.&lt;/p&gt;

&lt;p&gt;3- &lt;strong&gt;Efficient Data Fetching:&lt;/strong&gt; Only the necessary data is fetched from the database, which improves performance.&lt;/p&gt;

&lt;p&gt;4- &lt;strong&gt;Supports Expression Trees:&lt;/strong&gt; It builds an expression tree that is converted into SQL commands, allowing database-level operations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using (var context = new ApplicationDbContext())
{
    IQueryable&amp;lt;User&amp;gt; users = context.Users.Where(u =&amp;gt; u.IsActive);

    foreach (var user in users)
    {
        Console.WriteLine(user.Name);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, only the filtered data (&lt;strong&gt;IsActive&lt;/strong&gt; users) is fetched from the database, optimizing memory usage and execution time.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🚀 Key Differences Between &lt;em&gt;IEnumerable&lt;/em&gt; and &lt;em&gt;IQueryable&lt;/em&gt;&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4hyxd11w7v3lq4ii9zhd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4hyxd11w7v3lq4ii9zhd.png" alt="Image description" width="799" height="399"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;✅ Best Practices&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;1- &lt;strong&gt;Use &lt;em&gt;IQueryable&lt;/em&gt; for Database Queries:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If you are querying from a database, prefer IQueryable to avoid unnecessary data loading into memory.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2- &lt;strong&gt;Avoid Multiple Iterations:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Iterating multiple times over an &lt;em&gt;IQueryable&lt;/em&gt; query will re-execute the database query each time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3- &lt;strong&gt;Minimize Client-side Operations on &lt;em&gt;IQueryable&lt;/em&gt;:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Avoid calling methods like &lt;em&gt;.ToList()&lt;/em&gt; or &lt;em&gt;.AsEnumerable()&lt;/em&gt; too early; it triggers data loading.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;4- &lt;strong&gt;Use &lt;em&gt;IEnumerable&lt;/em&gt; for In-memory Collections:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When working with collections already in memory, &lt;em&gt;IEnumerable&lt;/em&gt; is sufficient and avoids extra overhead.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;5- &lt;strong&gt;Combine When Necessary:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If you need to perform additional client-side operations, use &lt;em&gt;.AsEnumerable()&lt;/em&gt; on an &lt;em&gt;IQueryable&lt;/em&gt; to switch context.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var result = context.Users.Where(u =&amp;gt; u.IsActive).AsEnumerable()
                          .Where(u =&amp;gt; u.Age &amp;gt; 30);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;❌ Common Mistakes to Avoid&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;1- &lt;strong&gt;Eager Conversion to List:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Calling &lt;em&gt;.ToList()&lt;/em&gt; too soon forces all records to be fetched before further filtering.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2- &lt;strong&gt;Multiple Enumerations:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Avoid iterating over the query multiple times; use &lt;em&gt;.ToList()&lt;/em&gt; if you must enumerate it multiple times.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3- &lt;strong&gt;Ignoring Deferred Execution:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Be mindful that queries are not executed until enumeration; changes to the query expression will be reflected in execution.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;4- &lt;strong&gt;Incorrect Usage for In-memory Collections:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using &lt;em&gt;IQueryable&lt;/em&gt; for in-memory operations adds unnecessary overhead and complexity.
&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Understanding the differences and best practices for &lt;strong&gt;IEnumerable&lt;/strong&gt; and &lt;strong&gt;IQueryable&lt;/strong&gt; can greatly improve the performance and maintainability of your .NET applications. Choose the right interface based on your data source and query requirements.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>ienumerable</category>
      <category>iqueryable</category>
    </item>
    <item>
      <title>Top .NET Interview Questions for 2024-2025</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Sat, 17 May 2025 07:36:21 +0000</pubDate>
      <link>https://dev.to/masterpars/top-net-interview-questions-for-2024-2025-ac3</link>
      <guid>https://dev.to/masterpars/top-net-interview-questions-for-2024-2025-ac3</guid>
      <description>&lt;p&gt;This article compiles the most frequently asked technical interview questions for .NET developers during 2024 and 2025. These questions are based on real-world experiences and trusted sources to help you better prepare for your upcoming technical interviews.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;🧠 .NET Basics and Architecture&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. What is the difference between .NET Framework and .NET Core?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;.NET Framework is designed for Windows applications, whereas .NET Core is a cross-platform, open-source version suitable for Windows, Linux, and macOS. From .NET 5 onwards, both are unified into a single platform known as .NET.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. What is CLR and what are its responsibilities?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;CLR (Common Language Runtime) is the execution environment for .NET applications, responsible for memory management, garbage collection, exception handling, and type safety.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. What are Assemblies in .NET?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Assemblies are executable (.exe) or library (.dll) files that contain compiled code and metadata required for .NET applications. They play a crucial role in versioning, security, and deployment.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;💡 Advanced C# and OOP Concepts&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;4. What is the difference between a Class and an Interface?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Classes can have implementation, fields, and properties, while Interfaces only define method signatures and properties without implementation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;5. What is the difference between an Abstract Class and an Interface?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Abstract classes can have both defined and undefined methods, whereas Interfaces only contain method signatures.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;6. What is the difference between ref and out parameters?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ref parameters must be initialized before being passed, while out parameters do not require initialization and are used for returning values from methods.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;7. What is LINQ and what are its benefits?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LINQ (Language Integrated Query) allows developers to write queries directly in C# for collections, databases, and XML, making code more readable and maintainable.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🧩 Advanced Concepts and Optimization&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;8. What is the difference between IEnumerable and IQueryable?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;IEnumerable is suitable for in-memory collections and executes queries in memory, while IQueryable is designed for database operations and executes queries at the database level.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;9. What is Dependency Injection and its benefits?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Dependency Injection (DI) is a design pattern that injects dependencies into classes, improving testability and maintainability. ASP.NET Core has built-in support for DI.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;10. What is the difference between Task and Thread?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Thread is a basic unit of execution, while Task is a higher-level abstraction for asynchronous programming that manages resources more efficiently.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;11. What is the role of async and await in C#?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;These keywords simplify asynchronous programming, allowing long-running operations without blocking the main thread.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🛠️ ASP.NET Core and Web API&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;12. How does the MVC pattern work in ASP.NET?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;MVC (Model-View-Controller) divides an application into three interconnected components to separate business logic from UI.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;13. How do you implement a RESTful API in .NET?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using ASP.NET Core Web API, developers define controllers with specific routes, create data models, and leverage Dependency Injection for service management.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;14. How do you secure a Web API?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using JWT for authentication, enabling HTTPS, and applying authorization policies and filters in ASP.NET Core.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🗃️ Database and Entity Framework&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;15. What is Entity Framework and its advantages?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Entity Framework (EF) is an ORM (Object-Relational Mapper) that allows developers to interact with databases using .NET objects instead of SQL queries.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;16. What is the difference between Lazy Loading and Eager Loading?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Lazy Loading loads data only when it is accessed, while Eager Loading fetches all related data along with the main entity.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;17. What is the difference between Clustered and Non-Clustered Indexes in SQL Server?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A Clustered Index sorts and stores data rows in the table, while a Non-Clustered Index maintains a separate structure pointing to the actual data.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;🧰 Tools and Best Practices&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;18. What is NuGet and its purpose?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;NuGet is a package manager for .NET that allows developers to add libraries and dependencies to their projects easily.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;19. How do you optimize the performance of a .NET application?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;By caching data, reducing database queries, using asynchronous programming, and managing resources efficiently.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;20. What are common design patterns in .NET?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Patterns like Singleton, Repository, and Factory are used for resource management, data abstraction, and object creation without exposing the instantiation logic.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>interview</category>
    </item>
    <item>
      <title>Discover What's New in EF Core 10</title>
      <dc:creator>Ali Shahriari (MasterPars)</dc:creator>
      <pubDate>Sat, 17 May 2025 06:40:43 +0000</pubDate>
      <link>https://dev.to/masterpars/discover-whats-new-in-ef-core-10-3n6i</link>
      <guid>https://dev.to/masterpars/discover-whats-new-in-ef-core-10-3n6i</guid>
      <description>&lt;p&gt;Entity Framework Core 10 (EF10) is the latest evolution of Microsoft's ORM, bringing significant enhancements to database interactions, especially with Azure Cosmos DB, LINQ translations, and update operations. In this article, we’ll explore the key features that make EF10 a game-changer for .NET developers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Enhanced Azure Cosmos DB Support
&lt;/h2&gt;

&lt;p&gt;EF10 introduces new capabilities for Azure Cosmos DB:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Full-Text Search Integration
: Cosmos DB now supports full-text search, allowing for efficient querying of text content directly in EF10. This is especially useful for AI-driven applications where relevance and search optimization are crucial.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; public class Blog
{
    public string Contents { get; set; }
}

public class BloggingContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&amp;lt;Blog&amp;gt;(b =&amp;gt;
        {
            b.Property(x =&amp;gt; x.Contents).EnableFullTextSearch();
            b.HasIndex(x =&amp;gt; x.Contents).IsFullTextIndex();
        });
    }
}

var results = await context.Blogs.Where(x =&amp;gt; EF.Functions.FullTextContains(x.Contents, "cosmos")).ToListAsync();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Hybrid Search Capabilities
: Leveraging RRF (Reciprocal Rank Fusion), EF10 now enables hybrid search, blending full-text search with vector-based searches for more accurate results.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; float[] myVector = /* vector data */;
var hybridResults = await context.Blogs.OrderBy(x =&amp;gt; EF.Functions.Rrf(
    EF.Functions.FullTextScore(x.Contents, "database"),
    EF.Functions.VectorDistance(x.Vector, myVector)
)).Take(10).ToListAsync();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Vector Similarity Search Maturity
: The experimental vector search feature from EF9 is now fully supported in EF10, with improvements for owned reference entities.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  New LINQ Operators for Joins
&lt;/h2&gt;

&lt;p&gt;.NET 10 simplifies LINQ joins with native LeftJoin and RightJoin methods. Previously, these joins required complex combinations of SelectMany and GroupJoin. Now, they are much more intuitive:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; var query = context.Students
    .LeftJoin(
        context.Departments,
        student =&amp;gt; student.DepartmentID,
        department =&amp;gt; department.ID,
        (student, department) =&amp;gt; new
        {
            student.FirstName,
            student.LastName,
            Department = department.Name ?? "[NONE]"
        });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Simplified Update Operations
&lt;/h2&gt;

&lt;p&gt;EF10 introduces an easier way to perform updates with ExecuteUpdateAsync, supporting lambda expressions directly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; await context.Blogs.ExecuteUpdateAsync(s =&amp;gt;
{
    s.SetProperty(b =&amp;gt; b.Views, 8);
    if (nameChanged)
    {
        s.SetProperty(b =&amp;gt; b.Name, "Updated Blog Name");
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This eliminates the need for cumbersome expression trees, making code cleaner and more maintainable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;EF Core 10 is set to make database interactions smoother and more efficient. Its enhancements in Cosmos DB support, LINQ simplifications, and update handling will undoubtedly be welcomed by .NET developers. Stay tuned for deeper dives into each of these features in upcoming tutorials.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>ef10</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
