Saturday, June 29, 2024

Entity Framework Core Topics

Entity Framework Core interview questions you might encounter:

1.      How does Entity Framework Core handle data concurrency conflicts?

·         EF Core uses optimistic concurrency control. When multiple users try to modify the same record simultaneously, it checks if the record has changed since it was loaded. If so, it throws a DbUpdateConcurrencyException.

2.      What are the core differences between Entity Framework 6 and Entity Framework Core?

·         EF Core is lightweight, cross-platform, and designed for modern applications. It lacks some features of EF 6 (e.g., lazy loading, EDMX designer), but offers better performance and flexibility.

3.      How would you map a database schema to entities in Entity Framework Core?

·         Use data annotations or Fluent API to define relationships, keys, and constraints. Customize the model by configuring entity properties and navigation properties.

When optimizing performance in Entity Framework Core (EF Core), consider the following strategies:

Retrieve Only Necessary Data:

Fetch only the columns you need from the database. Use .Select() to project specific properties and minimize data retrieval.

Split Large Data Contexts:

Divide a large data context into smaller ones. This can improve performance by reducing the overhead of tracking entities.

Batch Updates:

For bulk updates, use batch operations (SaveChanges() with multiple entities). This reduces the number of database round trips.

Disable Change Tracking for Read-Only Queries:

If you’re querying data for read-only purposes, disable change tracking to avoid unnecessary overhead.

DbContext Pooling:

Reuse DbContext instances using pooling. This minimizes the cost of creating and disposing of contexts.

Use IQueryable Instead of IEnumerable:

Prefer IQueryable over IEnumerable for better query translation and execution.

Eager Loading:

Explicitly load related entities using .Include() to avoid lazy loading overhead.


DbContext pooling is a feature in Entity Framework Core (EF Core) that helps improve performance and resource utilization when working with database contexts. Let’s dive into the details:

What is DbContext?

DbContext is a fundamental class in EF Core. It represents a session with the database and provides an abstraction over the underlying database connection. It allows you to query, insert, update, and delete data.

Why Use DbContext Pooling?

Creating a new DbContext instance for every database operation can be expensive. It involves overhead such as connection establishment, model initialization, and change tracking setup.

DbContext pooling addresses this by reusing existing instances, reducing the overhead of creating new contexts.

How Does DbContext Pooling Work?

When you enable pooling, EF Core maintains a pool of pre-initialized DbContext instances.

When you request a context, it’s taken from the pool (if available) rather than creating a new one.

After use, the context is returned to the pool for reuse.

Enabling DbContext Pooling:

To enable pooling, set the UseDbContextPooling option in your DbContext configuration:

C#

services.AddDbContext<MyDbContext>(options =>

{

    options.UseSqlServer(connectionString);

    options.UseDbContextPooling();

});

DbContext pooling is most beneficial in scenarios with frequent short-lived database operations (e.g., web applications).

Be cautious with long-lived contexts (e.g., background services) as they may accumulate state over time.


Fluent API in Entity Framework Core (EF Core) allows you to configure domain classes and override conventions without modifying your entity classes directly. It provides fine-grained control over how your entities map to database tables.

Fluent API and DbContext Configuration:

The most powerful way to configure your model in EF Core is by overriding the OnModelCreating method in your derived context.

Within this method, you can use Fluent API to specify how entities map to tables, define relationships, and more.

Fluent API configuration has the highest precedence and overrides conventions and data annotations.


1.      Conventions:

o   Conventions are the default rules that EF Core follows to map your domain model to the database schema.

o   For example, EF Core assumes that a property named Id is the primary key, and it pluralizes entity names to find corresponding table names.

o   Conventions simplify development by providing sensible defaults.

2.      Data Annotations:

o   Data annotations are attributes you apply directly to your entity classes or properties.

o   They allow you to customize aspects of the model, such as specifying column names, defining keys, or setting data types.

o   Examples include [Key], [Column], and [MaxLength].

3.      Fluent API:

o   Fluent API provides a more flexible and explicit way to configure your model.

o   You override the OnModelCreating method in your DbContext and use fluent methods to define mappings, relationships, and other details.

o   It allows fine-grained control, such as specifying composite keys, unique constraints, and custom column names.

4.      Precedence:

o   When there’s a conflict between conventions, data annotations, and fluent configuration, fluent configuration wins.

o   If you explicitly configure something using fluent API, it overrides any conventions or data annotations related to the same aspect.

Fluent API in Entity Framework Core (EF Core), you can specify which properties form the composite key. Here’s an example:

Suppose we have an entity named Employee with properties Id and Name. We want to create a composite key using both properties. Here’s how you can do it:

C#

public class Employee 

{

    public int Id { get; set; }

    public string Name { get; set; }

}

 

public class YourContext : DbContext

{

    public DbSet<Employee> employee { get; set; }

 

    protected override void OnModelCreating(ModelBuilder modelBuilder)

    {

        modelBuilder.Entity<Employee>().HasKey(emp => new { emp.Id, emp.Name });

    }

}

In this example, the HasKey method specifies that the composite key consists of both Id and Name. This ensures uniqueness based on the combination of these properties

Share:

Monday, June 24, 2024

What is static

  • A static class cannot contain any non-static members except const and enum.
  • A static class cannot inherit from other classes except the Object class. 
  • A static classes cannot implement interfaces. 
  • A static classes cannot be inherited because they are implicitly sealed by default. 
  • A static class cannot contain any instance constructors. 
  • A static class cannot be explicitly marked as sealed because it is already sealed by default. 
  • A static class can contain enums. explicit private constructors are not allowed in a static class. 
  • Only a static constructor (implicitly private) can be defined. 
  • A static class cannot be instantiated; it is implicitly abstract. 
  • A non-static class can contain static methods. 
  • A static method can be accessed using the class name itself, without creating an object of the class. 
  • A non-static class can also contain a static constructor. 
  • A static class cannot contain any destructor. an indexer cannot be defined in a static class because indexers cannot be static.
Share:

ASP.NET MVC request life cycle:

In ASP.NET MVC, understanding the request life cycle is essential for building robust web applications. Let’s explore the key stages of the ASP.NET MVC request life cycle
 
  Routing: 
  • When a client makes a request (e.g., visits a URL), the routing module processes it. 
  • The routing module maps the requested URL to a specific controller action based on predefined routes. 
  • Routes are defined in the RouteConfig.cs (or Startup.cs for ASP.NET Core) file. 
MVC Handler: 
  • Once the route is determined, the MVC handler is responsible for creating the appropriate controller instance. 
  • The controller is instantiated, and the action method is invoked. Controller Action Execution: 
  • The controller’s action method processes the request. 
  • It interacts with the model (data) and prepares the data to be displayed. 
  • The action method returns an ActionResult (e.g., a view, JSON, or redirect). 
View Result: 
  • The view engine processes the view result returned by the action method. 
  • It locates the corresponding view file (.cshtml) based on conventions. 
  • The view is rendered, and dynamic data is injected into the HTML. 
View Engine and View: 
  • The view engine compiles the view into HTML. 
  • The final HTML content is sent as the response to the client. 
  • The client’s browser renders the page. 
Application_End (Optional): 
  • If the application pool recycles or certain thresholds are exceeded, the Application_End event in Global.asax.cs is fired. 
  • This event allows you to perform cleanup tasks before the application shuts down.
Share:

Frequency of character in string

Using Dictionary:
string input = "Mahindra Thar Armada";
Dictionary charFrequency = new Dictionary();

foreach (char c in input)
{
    if (charFrequency.ContainsKey(c))
    {
        charFrequency[c]++;
    }
    else
    {
        charFrequency[c] = 1;
    }
}

// Print the character frequencies
foreach (var pair in charFrequency)
{
    Console.WriteLine($"{pair.Key} - {pair.Value}");
}

Using Linq Query:
var charFrequency = input
    .GroupBy(c => c)
    .ToDictionary(g => g.Key, g => g.Count());

// Print the character frequencies
foreach (var pair in charFrequency)
{
    Console.WriteLine($"{pair.Key} - {pair.Value}");
}
Using JavaScript
const frequencyOfChar = (arr) => {
    return arr.reduce((total, letter) => {
        total[letter] ? total[letter]++ : (total[letter] = 1);
        return total;
    }, {});
};


let input="Mahindra Thar Armada";
let arr=[...input];
const result = frequencyOfChar(arr);
console.log(result); // {"M": 1,"a": 5,"h": 2, "i": 1, "n": 1, "d": 2, "r": 3, " ": 2, "T": 1, "A": 1, "m": 1 }
Share: