08_Code First Approach with Dependency Injection and LINQ queries in .NET Console Application - Maniconserve/EF-Core GitHub Wiki
To enable Dependency Injection and Entity Framework Core, install the following NuGet packages:
Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.Configuration.Json
Instead of hardcoding the connection string, store it in an appsettings.json file.
{
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=SchoolDB;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
Create a model to represent the Students table.
using System.ComponentModel.DataAnnotations;
public class Student
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int Age { get; set; }
public string Grade { get; set; }
}
Define the database context to manage the Students
table.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
public class ApplicationDbContext : DbContext
{
private readonly IConfiguration _configuration;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IConfiguration configuration)
: base(options)
{
_configuration = configuration;
}
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"));
}
}
}
Configure Dependency Injection and execute LINQ queries.
using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using System.IO;
class Program
{
static void Main()
{
var serviceProvider = new ServiceCollection()
.AddSingleton<IConfiguration>(provider =>
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
return config;
})
.AddDbContext<ApplicationDbContext>()
.BuildServiceProvider();
using var context = serviceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
InsertSampleData(context);
PerformLINQQueries(context);
}
static void InsertSampleData(ApplicationDbContext context)
{
if (!context.Students.Any())
{
context.Students.AddRange(
new Student { Name = "Mani", Age = 22, Grade = "A" },
new Student { Name = "Pranav", Age = 20, Grade = "B" },
new Student { Name = "Bhaskar", Age = 21, Grade = "A" },
new Student { Name = "Vivek", Age = 23, Grade = "C" }
);
context.SaveChanges();
}
}
static void PerformLINQQueries(ApplicationDbContext context)
{
var student = context.Students.FirstOrDefault(s => s.Name == "Mani");
Console.WriteLine($"Search Result: {student?.Name} - Age: {student?.Age}, Grade: {student?.Grade}");
var filteredStudents = context.Students.Where(s => s.Age > 21).ToList();
Console.WriteLine("Students Older than 21:");
filteredStudents.ForEach(s => Console.WriteLine($"{s.Name}, Age: {s.Age}"));
var groupedStudents = context.Students.GroupBy(s => s.Grade)
.Select(g => new { Grade = g.Key, Count = g.Count() });
Console.WriteLine("\n Students Grouped by Grade:");
foreach (var group in groupedStudents)
{
Console.WriteLine($"Grade {group.Grade}: {group.Count} students");
}
}
}
Initialize Migrations
Add-Migration InitialCreate
Apply Migrations
Update-Database