Monday, 15 September 2025

Protecting SignalR and gRPC Apps in ASP.NET Core

Leave a Comment

A key component of contemporary apps is real-time communication. For this, ASP.NET Core offers two robust frameworks:

  • gRPC is a high-performance RPC framework suitable for microservices and backend communication.

  • SignalR → real-time web communication framework for pushing updates to clients.

 

Because these technologies involve persistent connections and high-frequency data exchange, security is critical to prevent eavesdropping, impersonation, and denial of service.

This article explores practical security strategies for both gRPC and SignalR in ASP.NET Core.

1. Security Challenges in Real-Time Communication
  • Unauthorized Access: Clients connecting without proper authentication.

  • Data Leakage: Unencrypted messages intercepted over the network.

  • Message Tampering: Modified requests or injected payloads.

  • DoS Attacks: Malicious clients keep connections open or flood the server.

  • Multi-tenant Risks: Ensuring one client cannot access another client’s data.

2. Securing gRPC in ASP.NET Core
2.1. Enforce Transport Layer Security (TLS)

gRPC requires HTTP/2, which works best with TLS.

builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenAnyIP(5001, listenOptions =>
    {
        listenOptions.UseHttps("certificate.pfx", "certPassword");
    });
});

All gRPC calls should be made over https:// to prevent eavesdropping.

2.2. Authentication with JWT / OAuth2

Use JWT bearer tokens for secure client authentication.

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.Authority = "https://identity.example.com";
        options.TokenValidationParameters = new()
        {
            ValidateAudience = false
        };
    });

builder.Services.AddAuthorization();

Apply to gRPC services:

[Authorize]
public class OrderService : Order.OrderBase
{
    public override Task<OrderReply> GetOrder(OrderRequest request, ServerCallContext context)
    {
        // Authenticated user logic
    }
}
2.3. Client-Side Token Injection

Clients must send tokens in metadata:

var headers = new Metadata
{
    { "Authorization", $"Bearer {token}" }
};
var response = await client.GetOrderAsync(new OrderRequest { Id = 1 }, headers);
2.4. Input Validation and Limits
  • Use max message size limits to prevent large-payload attacks.

builder.Services.AddGrpc(options =>
{
    options.MaxReceiveMessageSize = 2 * 1024 * 1024; // 2 MB
    options.MaxSendMessageSize = 2 * 1024 * 1024;
});
  • Validate all inputs at the service level.

2.5. Mutual TLS (mTLS) [Optional]

For extra security in microservices, enforce client certificates:

listenOptions.UseHttps("server.pfx", "password", httpsOptions =>
{
    httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
});
3. Securing SignalR in ASP.NET Core

3.1. Use HTTPS for Transport

Always host SignalR hubs over TLS.

app.UseHttpsRedirection();
3.2. Authentication with JWT or Cookies

SignalR integrates seamlessly with ASP.NET Core Authentication.

Server configuration:

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.Authority = "https://identity.example.com";
        options.TokenValidationParameters = new()
        {
            ValidateAudience = false;
        };

        // Enable for WebSockets
        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                var accessToken = context.Request.Query["access_token"];
                var path = context.HttpContext.Request.Path;
                if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/chathub"))
                {
                    context.Token = accessToken;
                }
                return Task.CompletedTask;
            }
        };
    });

Client connection:

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chathub", { accessTokenFactory: () => token })
    .build();
3.3. Authorization on Hub Methods
[Authorize(Roles = "Admin")]
public class ChatHub : Hub
{
    public async Task SendMessage(string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", Context.User?.Identity?.Name, message);
    }
}
3.4. Protect Against Abuse
  • Limit hub connections per user/IP.

  • Disconnect idle clients.

  • Rate limit messages per connection.

Example: throttling middleware for SignalR:

public override async Task OnConnectedAsync()
{
    if (TooManyConnections(Context.ConnectionId))
    {
        Context.Abort();
    }
    await base.OnConnectedAsync();
}
3.5. Data Validation

Since SignalR uses JSON/MessagePack, validate all incoming data to prevent injection attacks.

3.6. Cross-Origin Security (CORS)

Allow only trusted domains:

builder.Services.AddCors(options =>
{
    options.AddPolicy("SignalRCors", policy =>
    {
        policy.WithOrigins("https://trustedclient.com")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});
app.UseCors("SignalRCors");
4. Common Security Best Practices

Always use TLS for transport security.
Authenticate clients using JWT/OAuth2.
Use authorization attributes at the service/hub level.
Limit message size, rate, and connection count.
Validate all inputs to avoid injection.
Use centralized logging and monitoring (e.g., Application Insights, ELK).

5. Conclusion

Securing gRPC and SignalR in ASP.NET Core requires a layered approach:

  • Use TLS/mTLS for transport security.

  • Enforce JWT/OAuth2 authentication at the connection level.

  • Implement authorization policies for fine-grained access.

  • Apply limits, validation, and monitoring to detect and block malicious behavior.

By combining these patterns, developers can build secure, resilient, and real-time ASP.NET Core applications that protect both data and infrastructure.

Read More...

Tuesday, 9 September 2025

DateTime Functions in C# and .NET

Leave a Comment

In .NET, what is DateTime?
A.NET struct called DateTime is used to express dates and times with a precision of 100 ticks, or nanoseconds. System Assembly namespace: mscorlib.dll

Creating DateTime Instances

// Current date and time (system clock)
DateTime now = DateTime.Now;

// Current UTC time
DateTime utcNow = DateTime.UtcNow;

// Only current date, time set to 00:00:00
DateTime today = DateTime.Today;

// Specific date
DateTime specificDate = new DateTime(2025, 9, 8); // YYYY, MM, DD

// Specific date and time
DateTime specificDateTime = new DateTime(2025, 9, 8, 14, 30, 0); // YYYY,MM,DD,HH,MM,SS

Properties of DateTime

PropertyDescriptionExample
DateReturns the date part only (time = 00:00:00)now.Date
DayDay of the month (1-31)now.Day
MonthMonth (1-12)now.Month
YearYear componentnow.Year
DayOfWeekEnum representing day of weekDayOfWeek.Monday
DayOfYearDay number in the year (1-366)now.DayOfYear
TimeOfDayReturns a TimeSpannow.TimeOfDay
Hour, Minute, Second, MillisecondComponents of timenow.Hour

Common DateTime Methods

🧾Static Methods

DateTime current = DateTime.Now;

// Parsing
DateTime parsed = DateTime.Parse("2025-09-08");
DateTime parsedExact = DateTime.ParseExact("08-09-2025", "dd-MM-yyyy", null);

// Comparing
int result = DateTime.Compare(DateTime.Now, DateTime.UtcNow); // -1, 0, 1

// Check Leap Year
bool isLeap = DateTime.IsLeapYear(2024);

Instance Methods for Manipulation

DateTime today = DateTime.Today;

DateTime tomorrow = today.AddDays(1);       // Add days
DateTime lastWeek = today.AddDays(-7);      // Subtract days
DateTime nextMonth = today.AddMonths(1);    // Add months
DateTime lastYear = today.AddYears(-1);     // Subtract years
DateTime futureTime = today.AddHours(5);    // Add hours

Comparison Methods

DateTime a = DateTime.Now;
DateTime b = a.AddMinutes(10);

bool isEqual = a.Equals(b);    // false
int compare = a.CompareTo(b);  // -1 (a < b)

bool after = a > b;            // false
bool before = a < b;           // true

Formatting Methods

DateTime now = DateTime.Now;

// ToString with custom format
string formatted = now.ToString("dd/MM/yyyy HH:mm:ss");

// Predefined formats
string longDate = now.ToLongDateString();  // Monday, September 8, 2025
string shortDate = now.ToShortDateString(); // 9/8/2025
string longTime = now.ToLongTimeString();  // 4:25:30 PM
string shortTime = now.ToShortTimeString(); // 4:25 PM

Time Zones

DateTime utcNow = DateTime.UtcNow;

// Convert to local time
DateTime local = utcNow.ToLocalTime();

// Specify kind explicitly
DateTime unspecified = DateTime.SpecifyKind(utcNow, DateTimeKind.Unspecified);

DateTimeOffset (Recommended for Modern Apps)

DateTimeOffset is often preferred because it stores both the date/time and the UTC offset, which avoids ambiguity when working across multiple time zones.

DateTimeOffset dto = DateTimeOffset.Now;
Console.WriteLine(dto.Offset); // e.g., +05:30

Best Practices

  • Prefer DateTime.UtcNow for logging, auditing, and storage — avoid timezone issues.

  • Use DateTimeOffset when time zones matter (multi-region apps).

  • Use TryParse or TryParseExact for safe conversions (avoid exceptions).

  • Always specify a format when serializing dates (ISO 8601 recommended: "yyyy-MM-ddTHH:mm:ssZ").

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Monday, 1 September 2025

EF Core: Using Enums as Strings

Leave a Comment

Choosing how to store enums in your database is one of the minor choices that can have a big influence when working with Entity Framework Core (EF Core). EF Core saves enums as integers by default. Performance-wise, that's OK, but let's face it, a 2 or 3 in a database field doesn't really tell you anything. What does the number three mean? "Shipped" ? "Canceled" ? To discover out, you would need to look at the code.


However, what if "Shipped" could be stored directly in place of 3? EF Core makes it surprisingly simple to save enums as strings in this situation.

Why Bother Storing Enums as Strings?
It’s Just More Readable

When someone is reviewing the database, whether a support representative, analyst, or even you six months from now, a value like "Delivered" is immediately apparent. You don’t need to guess or cross-reference your codebase.

Easier Debugging and Maintenance

String values make logs, queries, and even reports easier to understand—no need to mentally decode what each number means.

Safer Long-Term
If you ever add or reorder enum members in your code, integer values can suddenly point to the wrong thing. Strings avoid this; the value stays the same regardless of its position in the enum.

How to Do It in EF Core?

Thankfully, EF Core provides a HasConversion() method that makes this process extremely straightforward.

Step-by-Step Example
1. Define an enum

public enum OrderStatus
{
    Pending,
    Processing,
    Shipped,
    Delivered
}

2. Use it in your model

public class Order
{
    public int Id { get; set; }
    public OrderStatus Status { get; set; }
}

3. Add this to your DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
        .Property(o => o.Status)
        .HasConversion<string>();
}


That’s it. Now EF Core will store the enum values as strings, such as "Pending" or "Delivered", instead of numbers.

Real-World Example: E-commerce System
Let’s say you’re building an online store. You have an OrderStatus enum.

Pending , Paid , Packed , Shipped , Delivered , Cancelled .

Why does storing as strings help?
Anyone viewing the Orders table can understand the status without needing to dive into the code. Support teams and analysts can filter and search the data more easily. Even if you decide to insert a new status like Delayed , it won't mess up existing data.

When Not to Use Strings?
Let’s be fair — strings aren’t always the best choice.

High-Performance Systems

If you’re building something like a trading platform that stores millions of rows per day, those extra characters add up. Integers are faster to compare and take up less space.

Frequently Changing Enum Names
If you frequently rename your enum values (not just add new ones), string values can break things. The DB still retains the "OldValue" even after you rename it to "NewValue." Currently, there's a mismatch in the code.

Advanced: Custom Value Converters
Need a bit more control? EF Core lets you define custom converters.

var converter = new ValueConverter<OrderStatus, string>(
    v => v.ToString(),
    v => (OrderStatus)Enum.Parse(typeof(OrderStatus), v));

modelBuilder.Entity<Order>()
    .Property(e => e.Status)
    .HasConversion(converter);

This is handy if you want to localize, abbreviate, or format the string differently. 

Entity Framework Core 1.0 Hosting Recommendation

One of the most important things when choosing a good Entity Framework Core 1.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable Entity Framework Core 1.0, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast Entity Framework Core 1.0 hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its data centers are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFE guarantees 99.9% uptime for Entity Framework Core 1.0. And the engineers do regular maintenance and monitoring works to assure its Entity Framework Core 1.0 hosting are security and always up.

Read More...

Wednesday, 27 August 2025

ASP.NET Core Development with XoomCoreWeb Boilerplate

Leave a Comment

It shouldn't feel like a chore to start a new ASP.NET Core project. Access control, logging, audit trails, and onion architecture are all built into the open-source boilerplate XoomCoreWeb. It is accessible as a Visual Studio Template for easy installs and on GitHub for contributions.

Key Features

  • Onion Architecture for clean separation of concerns
  • Role-based Access Control (pre-configured authentication and authorization)
  • Entity Framework Core with Generic Repository
  • Serilog Logging & Audit Trail for compliance-ready apps
  • Standardized API Responses with CommonResponse<T>
  • Template-based Startup, create a full-featured solution in seconds

Install via Visual Studio Marketplace
You can install the template directly into Visual Studio from the marketplace.

Download from Marketplace

Or, if you prefer using the CLI, run.

dotnet new install XoomCoreWeb::1.0.0

After installation, you can create a new project.

dotnet new xoomcoreweb -n MyProjectName

Getting Started
Clone from GitHub (for source access and contributions).

git clone https://github.com/chotonmishaque/XoomCoreWeb.git
cd XoomCoreWeb
Update Database Connection: Edit Configurations/database.json with your DB settings.
{
  "DatabaseSettings": {
    "DBProvider": "mssql",
    "ConnectionString": "Server=.;Database=MyAppDb;User Id=sa;Password=YourPassword;"
  }
}

Run EF Migrations

update-database
Login with Demo Credentials

How to Contribute?
We want this boilerplate to grow with the community. Here’s how you can help.

Star the repo on GitHub
Fork it and build new featuresReport issues or request enhancements
Submit PRs for bug fixes or new ideas

Contribute here: GitHub – XoomCoreWeb
Next Steps

  • Add Swagger/OpenAPI support
  • Add Docker Compose for containerized startup
  • Add Unit & Integration Tests
  • Add Health Checks for production readiness


Final Thoughts
XoomCoreWeb is not just a boilerplate; it’s a foundation for building clean, scalable, and secure ASP.NET Core apps. Whether you install it via CLI, download from Marketplace, or contribute through GitHub, you’ll save time and build faster.

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...

Tuesday, 19 August 2025

The Definition of Blazor and the Significance of Learning It

Leave a Comment

Web development has traditionally required two languages: C# (or any backend language) for server-side logic and JavaScript for client-side interactivity. But what if you could build full-stack web applications using just C#? What’s where Blazor comes in. Blazor is a modern framework from Microsoft that allows developers to build interactive web UIs using C#, Razor, and .NET without writing JavaScript for most scenarios.

What is Blazor?

Blazor is part of ASP.NET Core and enables building single-page applications (SPAs) using C#. It uses a component-based architecture similar to Angular, React, and Vue but with the power of .NET.

Uses of Blazor

  1. We can write client-side logic in C# instead of JavaScript.
  2. Reuse your .NET libraries across the client and server.
  3. Build web apps faster if you already know C#.

Why Blazor?

  1. One language: C# everywhere, no need to switch between C# and JavaScript.
  2. Component-Based: Build reusable UI components.
  3. Full .NET Ecosystem: Use LINQ, Entity Framework, and other .NET libraries.
  4. Cross-Platform: Works on Windows, Linux, and macOS.

Blazor hosting models

Blazor comes with two main hosting models:

Blazor Server

  • Runs on the server.
  • UI updates are sent via SignalR connection.
  • Pros: Small download size, works on older browsers.
  • Cons: Requires constant server connection.

Blazor WebAssembly (WASM)

  • Runs directly in the browser using WebAssembly.
  • Pros: Truly client-side, works offline, scalable.
  • Cons: Larger initial download.

Note. You can choose the model depending on your application needs.

Example: The Counter App

When you create a new Blazor project, you’ll see a default Counter page. Let’s look at the code:

When Should You Use Blazor?

  1. You are a .NET developer and want to avoid heavy JavaScript.
  2. You need to build line-of-business apps, dashboards, or internal tools.
  3. You want full-stack development with C#.

Conclusion

Blazor is an exciting framework that brings the power of .NET to web development. It allows you to build rich, interactive UIs using C# and Razor without relying heavily on JavaScript.

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0.11 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

  

Read More...

Tuesday, 12 August 2025

Reasons to Avoid String Interpolation in Structured Logging in .NET

Leave a Comment

It’s easy to overlook how small differences in logging syntax can affect performance, log structure, and searchability.

Take this innocent-looking log:

logger.LogInformation("Hello " + name);

Now compare it to:

logger.LogInformation($"Hello {name}");

And finally, this one:

logger.LogInformation("Hello {Name}", name);

They all seem to do the same thing, right?

Well… not quite. Let’s dive into what really sets them apart and why you should care.

1. Logging with String Concatenation

This method involves building log messages by explicitly joining strings and variable values using concatenation operators.

string user = "Alice";
int id = 123;
logger.LogInformation("User " + user + " with ID " + id + " logged in.");

Drawbacks

  • You lose the ability to parse or query name as a separate field in structured log systems.
  • Performance hit, even if logging is disabled at Information level, the string is still evaluated in memory.
2. Logging with String Interpolation

String interpolation provides a more concise and readable syntax for embedding expressions.

string user = "Bob";
int id = 456;
logger.LogInformation($"User {user} with ID {id} logged in.");

Drawbacks: while more readable than concatenation

  • The interpolated message is still passed as a single string.
  • The string is formatted in memory regardless of the logging level.
3. Structured Logging

Structured logging involves emitting log data in a predefined, machine-readable format like JSON or key-value pairs, rather than plain text. 

It separates the log message template from the dynamic data, allowing for richer querying and analysis. example.

string user = "Charlie";
int id = 789;
logger.LogInformation("User {UserName} with ID {UserId} logged in.", user, id);

Advantages

  • Log data can be easily queried and filtered based on specific fields.
  • Enables efficient ingestion and processing by log aggregation and analysis tools like Serilog and Seq will extract {Name} as a named field.
  • Parameters are only processed if the log level is enabled.

Benchmarking results


Modern .NET logging is more than just writing strings to the console. If you’re using tools like Seq, structured logging unlocks their full power, with better filtering, alerting, and dashboards.

So the next time you’re tempted to log like this:

logger.LogInformation("User logged in: " + userId);

…try this instead:

logger.LogInformation("User logged in: {UserId}", userId);

Your future self and your DevOps team will thank you.

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...

Thursday, 7 August 2025

Which Techniques Work Best for Optimizing the Performance of EF Core?

Leave a Comment

Overview of EF Core Performance Enhancement
Although Entity Framework Core (EF Core) is a strong and adaptable ORM for.NET, improper use might result in performance snags. With real-world C# examples, we'll examine recommended practices for enhancing EF Core performance, lowering query latency, and guaranteeing effective memory usage.

1. For read-only queries, utilize AsNoTracking()
When you're just reading data, EF Core doesn't need to track entities by default. Turning off tracking decreases memory use and speeds up queries.

var users = context.Users
    .AsNoTracking()
    .ToList();
When to Use
  • In read-only queries
  • In reporting or dashboard views
  • When tracking adds unnecessary overhead
2. Project Only Required Columns with Select

Avoid fetching entire entities when you only need a few fields.

var names = context.Users
    .Select(u => u.Name)
    .ToList();
Benefits
  • Reduces payload size
  • Improves query performance
  • Avoids unnecessary joins and data hydration
3. Avoid the N+1 Query Problem

The N+1 issue happens when lazy loading causes multiple queries unintentionally.

Bad
var orders = context.Orders.ToList();

foreach (var order in orders)
{
    Console.WriteLine(order.Customer.Name); // Triggers a query each time
}

Good (Eager Loading)

var orders = context.Orders
    .Include(o => o.Customer)
    .ToList();
4. Use Batching with AddRange / UpdateRange

Instead of calling SaveChanges() repeatedly, batch your inserts or updates:

context.Users.AddRange(user1, user2, user3);
await context.SaveChangesAsync();
For large batches

Use libraries like EFCore.BulkExtensions to dramatically reduce insert/update time.

5. Prefer FirstOrDefault() or Any() Instead of Count()

Count() checks all matching rows. Use Any() if you just need to check existence.

// Slower
bool hasUsers = context.Users.Count() > 0;

// Faster
bool hasUsers = context.Users.Any();
6. Use Indexes on Frequently Queried Columns

EF Core doesn’t manage database indexes, you must define them manually or in your migrations:

modelBuilder.Entity<User>()
    .HasIndex(u => u.Email)
    .IsUnique();
When to Use
  • On columns used in WHERE, JOIN, or ORDER BY
  • For foreign keys or commonly filtered fields
7. Use ToList() or ToArray() at the Right Time

Don’t call ToList() too early if you can keep the query in-memory longer to add more filters or projections.

example:
var recentUsers = context.Users
    .Where(u => u.CreatedAt > DateTime.UtcNow.AddDays(-7))
    .Select(u => u.Name)
    .ToList(); // Only at the end!
8. Use Compiled Queries for High-Throughput Scenarios

Compiled queries cache the query translation step, reducing overhead on repeated execution.

private static readonly Func<AppDbContext, int, User?> _getUserById =
    EF.CompileQuery((AppDbContext context, int id) =>
        context.Users.FirstOrDefault(u => u.Id == id));

// Usage
var user = _getUserById(context, 5);
9. Cache Frequently Used Data
Don’t hit the database for static data. Use in-memory caching:
var roles = memoryCache.GetOrCreate("roles", entry =>
{
    entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
    return context.Roles.AsNoTracking().ToList();
});

Or use a distributed cache for multiple server environments.

10. Use async Queries for Scalability

Always prefer async versions of EF Core methods:

var user = await context.Users
    .FirstOrDefaultAsync(u => u.Email == "[email protected]");
Benefits
  • Prevents thread blocking
  • Improves scalability in web apps
11. Avoid Unnecessary Change Tracking and Detach When Needed

If you need to load and discard data without tracking:

context.Entry(entity).State = EntityState.Detached;

Useful in long-running contexts or background jobs to avoid memory bloat.

12. Profile Queries and Use Logging

Use tools like:

  • EF Core logging (ILogger)
  • MiniProfiler
  • SQL Server Profiler
  • Visual Studio Diagnostic Tools

To inspect:

  • Query duration
  • Redundant database calls
  • Unoptimized SQL generated by LINQ
13. Use Raw SQL for Complex Queries (When Necessary)

When LINQ becomes inefficient or unreadable:

var users = context.Users
    .FromSqlRaw("SELECT * FROM Users WHERE IsActive = 1")
    .AsNoTracking()
    .ToList();

Be cautious with SQL injection, parameterize your queries!

14. Use Route-Level Filtering in APIs

Instead of filtering in-memory or in the controller, do it in the query itself:

// Good
var result = await context.Users
    .Where(u => u.Role == "Admin")
    .ToListAsync();
Conclusion

EF Core is powerful, but performance can suffer without thoughtful design. Apply these best practices to:

  • Reduce latency
  • Minimize memory usage
  • Avoid costly database operations
  • Scale efficiently

A fast app is a happy app, optimize early, monitor often!

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.
Read More...