• Fluent API
  • Phone
  • Companies
  • Birga ko’p bog‘lanish (One-to-Many)




    Download 1,39 Mb.
    bet44/53
    Sana30.11.2023
    Hajmi1,39 Mb.
    #108476
    1   ...   40   41   42   43   44   45   46   47   ...   53
    Bog'liq
    Dasturiy injiniring

    Birga ko’p bog‘lanish (One-to-Many)
    Birga – ko’p tarzda tashkil qilingan bog‘lanishda bitta model boshqa modellar to’plamiga uzatmaga ega bo’ladi. Misol sifatida quyidagi modelni ko’rib chiqamiz. Bir kompaniya bir nechta turdagi telefonlarni ishlab chiqsin.

    public class Phone


    {
    public int Id { get; set; }
    public string Name { get; set; }

    public Company Company { get; set; }


    }

    public class Company


    {
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection Phones { get; set; }
    public Company()
    {
    Phones = new List();
    }
    }


    Fluent API orqali aloqa quyidagicha shakllantiriladi:
    modelBuilder.Entity()
    .HasMany(p => p.Phones)
    .WithRequired(p => p.Company);


    HasMany() metodi orqali Company va Phone ob’ektlari o'rtasida birga ko’p aloqa o’rnatiladi. WithRequired() metodi esa Phone klassining Company xususiyati qiymati bo’lishi shartligi talab qilinadi.
    Ushbu bog‘lanishga ega bo’lgan modellarga Phone modeli o’zida Companies jadvali bilan bog‘lanishni ta'minlovchi Company_Id tashqi kalitni o’zida saqlaydi:





    Tashqi kalitni sozlash
    EF da tashqi kalit va ustun nomi bizni qanoatlantirmasa, HasForeignKey() metodi orqali ushbu qiymatlarni qayta aniqlash mumkin. Buning uchun quyidagi koddan foydalanish mumkin:

    class Phone


    {
    public int Id { get; set; }
    public string Name { get; set; }

    public Company Company { get; set; }


    public int Manufacturer { get; set; }
    }

    Endi Companies jadvaliga tashqi kalitni ifodalovchi Manufacturer xususiyatini sozlaymiz:


    modelBuilder.Entity()


    .HasMany(p => p.Phones)
    .WithRequired(p => p.Company)
    .HasForeignKey(s => s.Manufacturer);



    Download 1,39 Mb.
    1   ...   40   41   42   43   44   45   46   47   ...   53




    Download 1,39 Mb.

    Bosh sahifa
    Aloqalar

        Bosh sahifa



    Birga ko’p bog‘lanish (One-to-Many)

    Download 1,39 Mb.