• HasRequired()
  • Birga bir aloqa (One-to-One)
  • Birga nol yoki bir bog‘lanish (One-to–Zero-or-One)




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

    Birga nol yoki bir bog‘lanish (One-to–Zero-or-One)
    Ushbu turdagi bog‘lanish orqali tashkil qilingan modelda bir modelga mos ikkinchi model bo’lishi shart emas. Masalan:

    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 Phone BestSeller { get; set; }


    }

    Ushbu klasslar asosida tashkil qilingan modelda telefon albatta o’zining ishlab chiqargan kompaniyasi haqidagi ma’lumotlarni o’zida saqlaydi. Ya’ni ushbu holda aloqa birga - nol yoki ko’p bog‘lanish kabi tashkil qilingan. Ushbu model Fluent API da quyidagicha tashkil qilinadi:


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    modelBuilder.Entity()
    .HasRequired(c => c.Company)
    .WithOptional(c => c.BestSeller);

    base.OnModelCreating(modelBuilder);


    }

    Ushbu kodda HasRequired() metodi Phone ob’ektning Company xususiyati albatta mavjud bo’lishi lozimligini anglatadi. WithOptional() metodi esa avvalgi ifodadagi Company va uning BestSeller xususiyati bilan aloqa shart emasligini anglatadi.


    Quyida ushbu birga - nol yoki ko’p bog‘lanish kabi tashkil qilingan model elementlari ustida so’rov amalga oshirilgan:

    using (FluentContext db = new FluentContext())


    {
    // Telefon va u ishlab chikilgan kompaniya xakidagi ma’lumotni chikarish
    IEnumerable ps = db.Phones.Include(p => p.Company);
    foreach (var item in ps)
    Console.WriteLine("{0} - {1} ", item.Name, item.Company.Name);
    }


    Birga bir aloqa (One-to-One)
    Ushbu aloqa orqali tashkil qilingan modelda har ikkala ob’ektda bir-biriga aloqa mavjud bo’lishi lozim:
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    modelBuilder.Entity()
    .HasRequired(c => c.Company)
    .WithRequiredPrincipal(c => c.BestSeller);
    //yoki
    //modelBuilder.Entity()
    // .HasRequired(c => c.BestSeller)
    // .WithRequiredPrincipal(c => c.Company);

    base.OnModelCreating(modelBuilder);


    }



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




    Download 1,39 Mb.

    Bosh sahifa
    Aloqalar

        Bosh sahifa



    Birga nol yoki bir bog‘lanish (One-to–Zero-or-One)

    Download 1,39 Mb.