MVC CORE DATABASE ENTEGRASYONU
July 2019 (0) Iptv 11/1/2025
NOT : MVC CORE DATABASE ENTEGRASYONU
01 – ORM (Object Relational Mapping) Nedir?
SaveChanges() metodunu çalıştırmayana kadar db üzerine kaydedilmez.02 - Entity Framework İle Code First Yaklaşımı
03 - Dependency Injection
Model (Entity) oluşturulmasıContext sınıfının oluşturulmasıInterface oluşturulmasıRepository oluşturulmasıDependency Injection ile Startup.cs içinde yapılmasıADIM 01 - Veritabanı Sınıflarını ( Entities ) Oluşturma
Entities dizini açılıp kullanılabileceği gibi, yeni bir class library projesi de açılarak modellemeler oluşturulabilir.
ID veya <modelName>ID isimlendirmelerinden biri verildiğinde, otomatik olarak bu kısım primary key olarak alınır.[Key] paramatresi verilmelidir.[Table(<tablo_adi>)] yazılabilir.
Navigation Property verildiğinde otomatik olarak ara tablo oluşuyordu.
// Table 1
public class Table1
{
public int ID { get; set; }
public string area { get; set; }
public List<Table1Table2> Table1Table2s { get; set; }
}
// Table 2
public class Table2
{
public int ID { get; set; }
public string area { get; set; }
public List<Table1Table2> Table1Table2s { get; set; }
}
// Ara Tablo
public class Table1Table2
{
public int Table1ID { get; set; }
public Table1 Table1 { get; set; }
public int Table2ID { get; set; }
public Table2 Table2 { get; set; }
}
// Context Sınıfı
public class ProjectContext : DbContext
{
public ProjectContext(DbContextOptions<ProjectContext> option)
: base(option) { }
public DbSet<Table1> Table1s { get; set; }
public DbSet<Table2> Table2s { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Table1Table2>().HasKey(k => new { k.Table1ID, k.Table2ID });
}
}
ADIM 02 - Veritabanı İşlemlerini Yönetecek Sınıfı ( Context ) Oluşturma
DAL adlı bir dizin oluşturup içinde oluşturmak, entity modellerle karıştırılmaması açısından daha uygundur. Bunun dışında ayrı bir class library projesi eklenerek de context sınıfı burada oluşturulabilir.DbContext sınıfından kalıtım almalıdır.
Ctor Metodunun Oluşturulması ve Modellerin bağlanması
DbSet<model> olmasına dikkat edilmelidir.using Microsoft.EntityFrameworkCore;
using Project.Models.Entities;
namespace Project.Models.DAL
{
public class ProjectContext : DbContext
{
// Database bağlantısının oluşturulması
public ProjectContext(DbContextOptions<ProjectContext> options)
:base(options) { }
// Modellerin tanıtılması
public DbSet<Person> People { get; set; }
public DbSet<Address> Addresses { get; set; }
}
}
Bağlantı Stringinin Oluşturulması ve Yapılandırılması
connection string'e ihtiyacımız vardır.
"SERVER=<server_adı> ; DATABASE=<db_adı> ; UID=<kullanıcı_adı> ; PWD=<parola>"Integrated Security=true yazılarak giriş yapılabilir.
Server=(localdb)\\mssqllocaldb;Database=<db_adı>;Trusted_Connection=TrueSQL Server Express Database Engine yapısının sadeleştirilmiş halidir ve programlama anında hızlı bir şekilde kullanmayı amaçlar.C:/Users/<user> altında bir *.mdf dosyası oluşturur ve burayı kullanır.SQL Server Object Explorer ile görüntülenebilir.Startup.cs dosyasına aşağıdaki ayarlamaları giriyoruz.public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connection = "Server=.;Database=_coreDeneme;UID=sa;PWD=123";
services.AddDbContext<ProjectContext>(
option => option.UseSqlServer(connection)
);
}
appsettings.jsonadlı bir dosyayı eklememiz gerekmektedir.
Add > New Item > ASP.NET Configuration File dosyası eklenebilir.WebConfig dosyasının yerine geçmektedir.{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
DefaultConnection, kendi yazacağımız bağlantı stringi ile değiştirildikten sonra Startup.cs içinde bağlantı için artık şöyle bir kod yazılabilir.public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<EfCoreDbContext>(
option => option.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")
));
}
Bağlantı bilgilerinin context sınıfı içinde oluşturulması
Startup.cs içinde veya appsettings.json içinde tanımlanıyordu.public class EfProjectContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
"Server=(localdb)\\mssqllocaldb;Database=ExampleProject;Trusted_Connection=True"
);
}
public DbSet<Person> People { get; set; }
public DbSet<Address> Addresses { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ProjectContext>();
}
UseSqlServer metodu kullanıldında bulunamıyor veya hata alınıyorsa, bu kütüphanenin projeye dahil edilmesi gerekmektedir. Bunun için projenin .csproj dosyası içine aşağıdaki kodların girilmesi gerekmektedir.<ItemGroup>
<PackageReference Include = "Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.2" />
</ItemGroup>
ADIM 03 - Migration İşlemleri
cmdaçılarak
Edit <project>.csproj yoluna gelip aşağıdaki kütüphaneyi ItemGroup tagları arasına ekliyoruz.<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0"></DotNetCliToolReference>Nuget Package Console ile
dotnet ef migrations add <migration_name>
Add-Migration <migration_name>
dotnet ef database update
Update-Database
-Context parametresi kullanılmalıdır.Add-Migration <migration_name> -Context <context_name>Update-Database -Context <context_name>
-c veya --context parametreleri kullanılabilir.dotnet ef migrations add <migration_name> -c <context_name>dotnet ef database update -c <context_name>Migrations dizini altında bulunurken, sonra yapılanlar bu dizin altında yeni bir dizin açılarak otomatik olarak oluşturulur.context.Database.Migrate()metodunu kullanabiliriz.
ADIM 04 - Modellere Ait Interface Oluşturulması
public interface IPersonRepository
{
Person GetById(int personID);
IQueryable<Person> Persons { get; }
void CreatePerson(Person person);
void UpdatePerson(Person person);
void DeletePerson(int personID);
}
ADIM 05 - Interface'lerden Implament Edilen Repository Oluşturulması
public class SQLPersonRepository : IPersonRepository
{
private ProjectContext _context;
public SQLPersonRepository(ProjectContext context)
{
_context = context;
}
public Person GetById(int personID)
=> _context.People.FirstOrDefault(k => k.ID == personID);
public IQueryable<Person> Persons
=> _context.People;
public void CreatePerson(Person person)
{
_context.People.Add(person);
_context.SaveChanges();
}
public void UpdatePerson(Person person)
{
_context.Update(person);
_context.SaveChanges();
}
public void DeletePerson(int personID)
{
Person person = GetById(personID);
_context.Remove(person);
_context.SaveChanges();
}
}
ADIM 06 - Dependency Injection Bağlantısı
public void ConfigureServices(IServiceCollection services)
{
// Burada bağlantıyı yapıyoruz
services.AddTransient<IPersonRepository, SQLPersonRepository>();
var connection = "Server=.;Database=_coreDeneme;UID=sa;PWD=123";
services.AddDbContext<ProjectContext>(option => option.UseSqlServer(connection));
services.AddMvc();
}
04 - Seed Metotlar
Update-Database işlemi yapıldığında bu veriler işlenmez. Program ilk çalıştığında bu veriler işlenecektir.
Startup.cs içinde tanımlanmış ayarlara bağlı olduğu için (örn bağlantı string) direk olarak kullanılmaz.IServiceProviderüzerinden çekilmiştir.
var context = serviceProvider.GetRequiredService<EfProjectContext>();context.Database.Migrate();
Update-Database işlemi yapmamızı sağlar.FakeData eklentisi ile oluşturulmuştur.context.SaveChanges() metoduyla değişiklikleri kaydetmemiz gerekmektedir.public static class EfProjectContextSeed
{
public static void AddPeople(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetRequiredService<EfProjectContext>();
int peopleCount = 10;
context.Database.Migrate();
if (!context.Persons.Any())
{
for (int i = 0; i < peopleCount; i++)
{
context.Persons.Add(new Person
{
Name = FakeData.NameData.GetFirstName(),
Surname = FakeData.NameData.GetSurname()
});
}
context.SaveChanges();
}
}
}
Program.cs dosyası içindeki Main() metoduna entegre etmemiz gerekmektedir.var scope = host.Services.CreateScope() işlemiyle yeni bir ServiceProvider türetip kullanıyoruz.public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var service = scope.ServiceProvider;
EfProjectContextSeed.AddPeople(service);
}
host.Run();
}
05 - Geçici Database Oluşturma
UseInMemoryDatabase() metodunu kullanabiliriz.public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ExampleContext>(opt=>opt.UseInMemoryDatabase("ExampleDB"));
services.AddMvc();
}


