EFEF Core Handbook

REFERANS

Hızlı Referans Tablosu

En sık kullanılan Fluent API metodları ve SQL karşılıkları — hızlıca bakıp kopyalamak için.

Veritabanı sağlayıcısı Bu sayfadaki eşleşen örnekleri seçilen sağlayıcıya göre gösterir.
Metot Kullanım SQL Karşılığı
ToTable("T") Tablo adı CREATE TABLE [T]
ToView("V") View mapping — (var olan view)
HasKey(...) PK tanımla PRIMARY KEY
HasAlternateKey(...) Unique constraint UNIQUE
HasIndex(...) Index CREATE INDEX
HasIndex(...).IsUnique() Unique index CREATE UNIQUE INDEX
HasIndex(...).HasFilter(...) Filtered index WHERE ...
Property(...).IsRequired() NOT NULL NOT NULL
Property(...).HasMaxLength(n) Uzunluk NVARCHAR(n)
Property(...).HasColumnType(...) DB tipi Belirtilen tip
Property(...).HasDefaultValue(...) Sabit default DEFAULT value
Property(...).HasDefaultValueSql(...) SQL default DEFAULT expr
Property(...).HasComputedColumnSql(...) Computed column AS (expr)
Property(...).IsRowVersion() Concurrency (timestamp) ROWVERSION
Property(...).IsConcurrencyToken() Concurrency token WHERE'de kontrol
Property(...).HasConversion<T>() Value converter — (uygulama katmanı)
HasOne(...).WithMany(...) 1-N ilişki FOREIGN KEY
HasOne(...).WithOne(...) 1-1 ilişki FOREIGN KEY + UNIQUE
HasMany(...).WithMany(...) N-N ilişki Join tablo
OwnsOne(...) Owned entity (tekil) Aynı tabloda sütunlar
OwnsMany(...) Owned entity (koleksiyon) Ayrı tablo
ComplexProperty(...) Complex type (EF8+) Aynı tabloda sütunlar
HasQueryFilter(...) Global filtre Otomatik WHERE
Ignore(...) Property'yi dışla Sütun oluşmaz
HasDiscriminator(...) TPH discriminator Discriminator sütunu
UseTptMappingStrategy() TPT kalıtım Her tip ayrı tablo
UseTpcMappingStrategy() TPC kalıtım Concrete tipler ayrı
HasSequence(...) Sequence tanımla CREATE SEQUENCE
UseHiLo(...) Hi-Lo key generation Sequence + batch
PrimitiveCollection(...) Primitive koleksiyon (EF8+) JSON array
AsNoTracking() Tracking kapat — (performans)
ExecuteUpdateAsync() Toplu güncelleme (EF7+) Tek UPDATE
ExecuteDeleteAsync() Toplu silme (EF7+) Tek DELETE
HasNoKey() Keyless entity (View/SP) Tablo oluşmaz
IsTemporal() Temporal table SYSTEM_VERSIONING = ON
TemporalAsOf(date) Belirli andaki veri FOR SYSTEM_TIME AS OF
TagWith("...") Query tag (profiling) SQL yorumu olarak eklenir
EF.CompileAsyncQuery(...) Compiled query Derleme cache'lenir
EnableRetryOnFailure(n) Connection resiliency Otomatik retry
AddDbContextPool(...) DbContext pooling Instance reuse
SplitToTable("T") Entity splitting (EF7+) Ayrı tabloya map
UseSeeding(...) Koşullu seed (EF9+) Runtime seed
EF.Functions.Like(...) LIKE sorgusu LIKE pattern
EF.Functions.DateDiffDay(...) Gün farkı DATEDIFF(DAY,...)

Örnek: Tam Bir Entity Configuration

Tam E-Ticaret ER Diyagramı:

Categories 🔑 int Id PK nvarchar Name Products 🔑 int Id PK nvarchar ProductName decimal Price nvarchar Sku UK int CategoryId FK bit IsActive bit IsDeleted datetime2 CreatedAt varbinary RowVersion ── Owned: Dimensions ── decimal Dim_Width decimal Dim_Height decimal Dim_Depth Customers 🔑 int Id PK nvarchar FullName nvarchar Email Orders 🔑 int Id PK nvarchar Reference int CustomerId FK datetime2 OrderDate OrderLineItems 🔑 int Id PK int OrderId FK int ProductId FK int Quantity decimal UnitPrice Payments 🔑 int Id PK decimal Amount int OrderId FK nvarchar PaymentType ↑ Discriminator (TPH) 1:N contains 1:N places 1:N in order 1:N has items 1:N paid by Legend: 🔑 PK = Primary Key FK = Foreign Key UK = Unique Owned = Value Object Discriminator = TPH Inheritance
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        // Tablo
        builder.ToTable("Products", "catalog", t =>
        {
            t.HasComment("Ürün ana tablosu");
        });

        // PK
        builder.HasKey(p => p.Id);
        builder.Property(p => p.Id).ValueGeneratedOnAdd();

        // Özellikler
        builder.Property(p => p.Name)
               .IsRequired()
               .HasMaxLength(200)
               .HasColumnName("ProductName")
               .HasComment("Ürün adı");

        builder.Property(p => p.Price)
               .HasPrecision(18, 2)
               .HasComment("KDV dahil satış fiyatı");

        builder.Property(p => p.CreatedAt)
               .HasDefaultValueSql("GETUTCDATE()")
               .ValueGeneratedOnAdd();

        builder.Property(p => p.RowVersion).IsRowVersion();

        // Index'ler
        builder.HasIndex(p => p.Sku)
               .IsUnique()
               .HasDatabaseName("UX_Products_Sku");

        builder.HasIndex(p => new { p.CategoryId, p.IsActive })
               .HasDatabaseName("IX_Products_Category_Active");

        // İlişki
        builder.HasOne(p => p.Category)
               .WithMany(c => c.Products)
               .HasForeignKey(p => p.CategoryId)
               .OnDelete(DeleteBehavior.Restrict);

        // Owned entity
        builder.OwnsOne(p => p.Dimensions, dim =>
        {
            dim.Property(d => d.Width).HasColumnName("Dim_Width");
            dim.Property(d => d.Height).HasColumnName("Dim_Height");
            dim.Property(d => d.Depth).HasColumnName("Dim_Depth");
        });

        // JSON kolonu
        builder.OwnsMany(p => p.Tags, t => t.ToJson());

        // Global query filter
        builder.HasQueryFilter(p => !p.IsDeleted);

        // Ignore
        builder.Ignore(p => p.DisplayPrice);
    }
}

Oluşan tam SQL:

CREATE TABLE [catalog].[Products] (
    [Id]            INT            IDENTITY(1,1) NOT NULL,
    [ProductName]   NVARCHAR(200)  NOT NULL,
    [Price]         DECIMAL(18,2)  NOT NULL,
    [Sku]           NVARCHAR(450)  NOT NULL,
    [CategoryId]    INT            NOT NULL,
    [IsActive]      BIT            NOT NULL,
    [IsDeleted]     BIT            NOT NULL,
    [CreatedAt]     DATETIME2      NOT NULL DEFAULT GETUTCDATE(),
    [RowVersion]    ROWVERSION     NOT NULL,
    [Dim_Width]     FLOAT          NULL,
    [Dim_Height]    FLOAT          NULL,
    [Dim_Depth]     FLOAT          NULL,
    [Tags]          NVARCHAR(MAX)  NULL,   -- JSON
    
    CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED ([Id]),
    CONSTRAINT [FK_Products_Categories_CategoryId] 
        FOREIGN KEY ([CategoryId]) REFERENCES [catalog].[Categories]([Id]) ON DELETE NO ACTION
);

CREATE UNIQUE NONCLUSTERED INDEX [UX_Products_Sku] 
    ON [catalog].[Products] ([Sku]);

CREATE NONCLUSTERED INDEX [IX_Products_Category_Active] 
    ON [catalog].[Products] ([CategoryId], [IsActive]);

CREATE NONCLUSTERED INDEX [IX_Products_CategoryId] 
    ON [catalog].[Products] ([CategoryId]);
CREATE TABLE catalog.products (
    id             INT            GENERATED BY DEFAULT AS IDENTITY,
    product_name   VARCHAR(200)   NOT NULL,
    price          NUMERIC(18,2)  NOT NULL,
    sku            VARCHAR(450)   NOT NULL,
    category_id    INT            NOT NULL,
    is_active      BOOLEAN        NOT NULL,
    is_deleted     BOOLEAN        NOT NULL,
    created_at     TIMESTAMPTZ    NOT NULL DEFAULT NOW(),
    xmin           xid            NOT NULL,   -- PostgreSQL concurrency token
    dim_width      DOUBLE PRECISION NULL,
    dim_height     DOUBLE PRECISION NULL,
    dim_depth      DOUBLE PRECISION NULL,
    tags           JSONB          NULL,
    
    CONSTRAINT pk_products PRIMARY KEY (id),
    CONSTRAINT fk_products_categories_category_id 
        FOREIGN KEY (category_id) REFERENCES catalog.categories(id) ON DELETE NO ACTION
);

CREATE UNIQUE INDEX ux_products_sku 
    ON catalog.products (sku);

CREATE INDEX ix_products_category_active 
    ON catalog.products (category_id, is_active);

CREATE INDEX ix_products_category_id 
    ON catalog.products (category_id);