Hisoblangan ustunlar (Computed Columns EF Core)

2023 Mar 19, 13:10 • Wahid Abduhakimov (@wahid)

Entity Framework (EF) Coredagi hisoblangan ustunlar (Computed Columns) DBdagi biror ustunni qiymatini tashqaridan kiritmasdan shunchaki hisoblab topib qiymat belgilash imkonini beradi.

HasComputedColumnSqlmethodi orqali hisoblangan ustinni belgilash mumkin. Misol uchun:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public decimal DiscountedPrice { get; set; }
}

// In your DbContext class:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>()
        .Property(p => p.DiscountedPrice)
        .HasComputedColumnSql("Price * 0.9");
}

Ushbu misolda bizda Id, Name va Price hususiyatlarga ega Product ob'ekti mavjud. Productda DiscountedPrice xususiyati ham bor, uning qiymatini tashqaridan kiritmasda Price xususiyati asosida hisoblaymiz. DiscountedPrice ni hisoblash uchun Price ni 0,9 ga ko'paytiruvchi SQL ifodasini belgilash uchun HasComputedColumnSql methodidan foydalanamiz.

Best Practice

Ob'ektning qiymatini tasodifan tashqaridan kiritish yoki o’zgaritirishni oldini olish uchun ComputedColumn (hisoblangan ustun) propertyga private set modifier bergan ma’qul. Sababi, ComputedColumns boshqa ustunlar yoki boshqa jadvaldagi qiymatlar asosida hisoblash uchun mo'ljallangan va bevosita o'zgartirilmasligi kerak.

Oldingi bo'limda keltirilgan misolda, DiscountedPrice property DatabaseGenerated(DatabaseGeneratedOption.Computed) atributiga ega ekanligiga e'tibor bering, lekin unga private set modifier berilmagan.

DiscountedPrice yangilangan na’munasi:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public decimal DiscountedPrice { get; private set; }
}

DiscountedPrice propertysiga private set qo'shish orqali biz uning qiymatini Product ob'ektidan tashqaridan o’zgartirib bo’lmasligini ta’minlaymiz. Shunday qilib, DiscountedPrice qiymati faqat DB tomonidan hisoblanishi va o’zgartirilishi mumkin.

252 marta ko'rildi
Wahid Abduhakimov - uzbekdevs photo

Wahid Abduhakimov

@wahid

Telegram Post

@uzbekdevs
“uzbekdevs.uz” saytida eʼlon qilingan materiallardan nusxa koʻchirish, tarqatish va boshqa shakllarda foydalanish faqat manba ko'rsatilishi orqali amalga oshirilishi mumkin.
© UzbekDevs