Posts

Showing posts from November, 2024

LINQ

LINQ: LINQ (Language Integrated Query) is a set of methods in .NET that allows you to query and manipulate data in a more declarative way using C# or other .NET languages. LINQ can be used to query various data sources, including collections in memory, databases, XML, and even remote data sources. Example:      You can use LINQ to query an array, list, or a database with SQL-like syntax but directly in C#. Types of LINQ:   1. LINQ to Objects: Queries collections such as arrays, lists, or other in-memory objects.   2. LINQ to SQL: Queries data in a SQL database via an ORM (Object-Relational Mapping), such as Entity Framework.   3. LINQ to XML: Used to query and manipulate XML data.   4. LINQ to Entities: Queries data in a database using Entity Framework. IEnumerable and IQueryable: IEnumerable:      Used for in-memory collections, supports deferred execution, and performs operations in memory without translating to an external query langu...

LINQ - Differences

 1. Queryable vs Enumerable in LINQ Queryable (found in System.Linq.Queryable) is used for LINQ queries that work with IQueryable collections. It is often used with databases or any collection that supports deferred execution (e.g., Entity Framework queries). The queries are translated into the provider's query language (like SQL). Enumerable (found in System.Linq.Enumerable) is used for LINQ queries on IEnumerable collections (like arrays, lists, or other in-memory collections). It is intended for querying collections that reside in memory and supports immediate execution. 2. Distinct vs GroupBy in LINQ Distinct: This method is used to return distinct (unique) elements from a collection, removing duplicates based on the equality of the elements. Example: var distinctNumbers = numbers.Distinct(); GroupBy: This method is used to group elements in a collection based on a key. It does not eliminate duplicates but groups them together. Example: var groupedNumbers = numbers.GroupBy(x =...

Dapper for insert into Tables using Stored Procedure in Dotnet core

 using Dapper; using System; using System.Data.SqlClient; public class User {     public int Id { get; set; }     public string Name { get; set; } } public class Program {     private static string connectionString = "YourConnectionStringHere";     public static void Main()     {         using (var connection = new SqlConnection(connectionString))         {             connection.Open();             var user = new User             {                 Name = "John Doe"             };             var sql = "InsertUser"; // Stored Procedure Name             var parameters = new { Name = user.Name };             var userId = connection.Query<int>(s...

Dapper for delete Tables in Dotnet core

 using Dapper; using System; using System.Data.SqlClient; public class Program {     private static string connectionString = "YourConnectionStringHere";     public static void Main()     {         using (var connection = new SqlConnection(connectionString))         {             connection.Open();             var userId = 1;             var sql = "DELETE FROM Users WHERE Id = @Id";             var affectedRows = connection.Execute(sql, new { Id = userId });             Console.WriteLine($"Number of rows deleted: {affectedRows}");         }     } }

Dapper for update Tables in Dotnet core

 using Dapper; using System; using System.Data.SqlClient; public class User {     public int Id { get; set; }     public string Name { get; set; } } public class Program {     private static string connectionString = "YourConnectionStringHere";     public static void Main()     {         using (var connection = new SqlConnection(connectionString))         {             connection.Open();             var user = new User             {                 Id = 1,                 Name = "Updated Name"             };             var sql = "UPDATE Users SET Name = @Name WHERE Id = @Id";             var affectedRows = connection.Execute(sql, user); ...

Dapper for insert into Tables in Dotnet core

 using Dapper; using System; using System.Data.SqlClient; public class User {     public int Id { get; set; }     public string Name { get; set; } } public class Program {     private static string connectionString = "YourConnectionStringHere";     public static void Main()     {         using (var connection = new SqlConnection(connectionString))         {             connection.Open();             var user = new User             {                 Name = "John Doe"             };             var sql = "INSERT INTO Users (Name) VALUES (@Name); SELECT CAST(SCOPE_IDENTITY() AS INT);";             var userId = connection.Query<int>(sql, user).Single();       ...

Dapper for fetching data from multiple Tables in Dotnet core

using Dapper; using System; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; public class User {     public int Id { get; set; }     public string Name { get; set; } } public class Order {     public int Id { get; set; }     public int UserId { get; set; }     public string Product { get; set; } } public class Program {     private static string connectionString = "YourConnectionStringHere";     public static void Main()     {         using (var connection = new SqlConnection(connectionString))         {             connection.Open();             // Fetch data from multiple tables             var sql = @"                 SELECT u.Id, u.Name, o.Id AS OrderId, o.Product            ...

how to use Dapper in a .NET Core application to fetch data from a database

Install Dapper NuGet package: dotnet add package Dapper Code to fetch data using Dapper: using Dapper; using System; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; public class User {     public int Id { get; set; }     public string Name { get; set; } } public class Program {     private static string connectionString = "YourConnectionStringHere";     public static void Main()     {         using (var connection = new SqlConnection(connectionString))         {             connection.Open();             // Fetch a single record             var user = connection.QueryFirstOrDefault<User>("SELECT Id, Name FROM Users WHERE Id = @Id", new { Id = 1 });             Console.WriteLine($"User: {user?.Name}");           ...

Migrating an ASP.NET MVC project to a .NET Core Web API with Entity Framework Core (EF Core) and Angular

 Migrating an ASP.NET MVC project to a .NET Core Web API with Entity Framework Core (EF Core) and Angular involves several key steps. Below is a step-by-step guide to perform the migration effectively: 1. Set Up the .NET Core Web API Project You need to create a new .NET Core Web API project, which will replace the MVC controllers and views with API controllers. Steps: 1.Create a New .NET Core Web API Project: ·        Open Visual Studio or VS Code. ·        Create a new project using the ASP.NET Core Web API template.   dotnet new webapi -n MyApiProject ·        Choose the correct .NET Core version (e.g., .NET 6 or .NET 7). ·        Name the project appropriately.   2.            Configure Routing and Controllers: In .NET Core, routing for API is based on controllers, typicall...

update a single column in Entity Framework Core (EF Core)

Update a single column in Entity Framework Core (EF Core): To update a single column in  Entity Framework Core (EF Core) , you can perform the update operation without loading the entire entity from the database. This is useful for optimizing performance when you only need to modify one specific property (column) of an entity. Steps to Update a Single Column: Retrieve the Entity (or part of it) : You can retrieve the entity, then update only the specific column you want to change. Set the Property Value : Set the value for the specific property/column you want to update. Save Changes : Save the changes to the database   Approach1: public async Task UpdateProductPriceAsync(int productId, decimal newPrice) {     var product = await _dbContext.Products.FindAsync(productId);         if (product != null)     {         product.Price = newPrice;     ...

how to connect to two databases in a .NET Core application using Entity Framework Core.

 how to connect to two databases in a .NET Core application using Entity Framework Core? 1. Create DbContext Classes for Each Database // DbContext for Database 1 public class Database1Context : DbContext {     public Database1Context(DbContextOptions<Database1Context> options) : base(options) { }       public DbSet<Product> Products { get; set; }     public DbSet<Customer> Customers { get; set; } }   // DbContext for Database 2 public class Database2Context : DbContext {     public Database2Context(DbContextOptions<Database2Context> options) : base(options) { }       public DbSet<Order> Orders { get; set; }     public DbSet<Invoice> Invoices { get; set; } } 2. Configure the DbContexts in Program.cs or Startup.cs var builder = WebApplication.CreateBuilder(args);   // Configure Database 1 builder.Services.A...