namespace ToDoAppExample.Models
public int TaskItemId { get; set; }
public string Description { get; set; }
public bool IsCompleted { get; set; }
public DateTime CreatedAt { get; set; }
using Microsoft.EntityFrameworkCore;
using ToDoAppExample.Models;
namespace ToDoAppExample.Data
public class ToDoContext : DbContext
public ToDoContext(DbContextOptions<ToDoContext> options) : base(options) { }
public DbSet<TaskItem> TaskItems { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseSqlServer("YourConnectionStringHere");
using System.Collections.Generic;
using System.Threading.Tasks;
using ToDoAppExample.Models;
namespace ToDoAppExample.Repositories
public interface ITaskRepository
Task<IEnumerable<TaskItem>> GetAllAsync();
Task<TaskItem> GetByIdAsync(int id);
Task AddAsync(TaskItem taskItem);
Task UpdateAsync(TaskItem taskItem);
Task DeleteAsync(int id);
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ToDoAppExample.Data;
using ToDoAppExample.Models;
namespace ToDoAppExample.Repositories
public class TaskRepository : ITaskRepository
private readonly ToDoContext _context;
public TaskRepository(ToDoContext context)
public async Task<IEnumerable<TaskItem>> GetAllAsync()
return _context.TaskItems.ToList();
public async Task<TaskItem> GetByIdAsync(int id)
return await _context.TaskItems.FindAsync(id);
public async Task AddAsync(TaskItem taskItem)
await _context.TaskItems.AddAsync(taskItem);
public async Task UpdateAsync(TaskItem taskItem)
_context.TaskItems.Update(taskItem);
await _context.SaveChangesAsync();
public async Task DeleteAsync(int id)
var taskItem = await _context.TaskItems.FindAsync(id);
_context.TaskItems.Remove(taskItem);
await _context.SaveChangesAsync();
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using ToDoAppExample.Data;
using ToDoAppExample.Models;
using ToDoAppExample.Repositories;
static async Task Main(string[] args)
var serviceProvider = new ServiceCollection()
.AddLogging(config => config.AddConsole())
.AddDbContext<ToDoContext>(options => options.UseSqlServer("YourConnectionStringHere"))
.AddScoped<ITaskRepository, TaskRepository>()
var taskRepository = serviceProvider.GetService<ITaskRepository>();
var taskItem = new TaskItem { Description = "Learn Entity Framework Core", IsCompleted = false, CreatedAt = DateTime.Now };
await taskRepository.AddAsync(taskItem);
Console.WriteLine($"Added Task: {taskItem.Description}");
var tasks = await taskRepository.GetAllAsync();
Console.WriteLine("Tasks:");
foreach (var task in tasks)
Console.WriteLine($"- {task.Description} (Completed: {task.IsCompleted})");