Dasturiy injiniring (EntityFramework 6)




Download 1,39 Mb.
bet27/53
Sana30.11.2023
Hajmi1,39 Mb.
#108476
1   ...   23   24   25   26   27   28   29   30   ...   53
Bog'liq
Dasturiy injiniring

LINQ to Entities so’rovlarini tavsiflashdan avval ushbu bo’lim uchun zarur bo’lgan modellarni aniqlab olamiz:
class Company
{
public int Id { get; set; }
public string Name { get; set; }

public ICollection Phones { get; set; }


public Company()
{
Phones = new List();
}
}

class Phone


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

public int CompanyId { get; set; }


public Company Company { get; set; }
}

Yuqorida telefon va ishlab chiquvchi kompaniya modeli keltirilgan. Endi ushbu modellarga mos ma’lumotlar konteksti va DB initsializatori orqali boshlang‘ich ma’lumotlarni shakllantiramiz.


class PhoneContext : DbContext
{
static PhoneContext()
{
Database.SetInitializer(new MyContextInitializer());
}
public PhoneContext()
: base("DBConnection")
{ }

public DbSet Companies { get; set; }


public DbSet Phones { get; set; }
}

class MyContextInitializer : DropCreateDatabaseAlways


{
protected override void Seed(PhoneContext db)
{
Company c1 = new Company { Name = "Samsung" };
Company c2 = new Company { Name = "Apple" };
db.Companies.Add(c1);
db.Companies.Add(c2);

db.SaveChanges();


Phone p1 = new Phone { Name = "Samsung Galaxy S5", Price = 20000, Company = c1 };


Phone p2 = new Phone { Name = "Samsung Galaxy S4", Price = 15000, Company = c1 };
Phone p3 = new Phone { Name = "iPhone5", Price = 28000, Company = c2 };
Phone p4 = new Phone { Name = "iPhone 4S", Price = 23000, Company = c2 };

db.Phones.AddRange(new List() { p1, p2, p3, p4 });


db.SaveChanges();
}
}
So’ngra App.config faylida ulanish satri hosil qilish lozim:





DBda boshlang‘ich ma’lumotlarni shakllantirish uchun initsializatorda bir nechta ob’ektlar hosil qilinadi. Initsializatorni ishga tushirish uchun u ma’lumotlar kontekstidagi statik konstruktorda chaqiriladi:
static PhoneContext()
{
Database.SetInitializer(new MyContextInitializer());
}

Download 1,39 Mb.
1   ...   23   24   25   26   27   28   29   30   ...   53




Download 1,39 Mb.

Bosh sahifa
Aloqalar

    Bosh sahifa



Dasturiy injiniring (EntityFramework 6)

Download 1,39 Mb.