ASP.NET Core + Entity Framework Core: Tam CRUD Uygulaması
Bilkey Bilişim Akademisi
30.03.2024
4 okunma
İLERİ DÜZEY C# ASP.NET YAZILIM
Proje Yapısı
MyApp/
├── Controllers/ → API endpoint'leri
├── Models/ → Entity sınıfları
├── DTOs/ → Veri transfer nesneleri
├── Data/ → DbContext
├── Repositories/ → Veri erişim katmanı
└── Services/ → İş mantığı
Entity ve DbContext
public class Urun {
public int Id { get; set; }
[Required, MaxLength(100)]
public string Ad { get; set; }
[Range(0, double.MaxValue)]
public decimal Fiyat { get; set; }
}
public class AppDbContext : DbContext {
public AppDbContext(DbContextOptions options) : base(options) { }
public DbSet<Urun> Urunler { get; set; }
}
Generic Repository
public class Repository<T> : IRepository<T> where T : class {
private readonly AppDbContext _ctx;
public Repository(AppDbContext ctx) => _ctx = ctx;
public async Task<IEnumerable<T>> GetAllAsync() =>
await _ctx.Set<T>().ToListAsync();
public async Task AddAsync(T entity) {
await _ctx.Set<T>().AddAsync(entity);
await _ctx.SaveChangesAsync();
}
}