Phone va PnoneInfo modellari bir xil birlamchi kalitga ega bo’lib, o'lar o’z navbatida ikkilamchi kalit vazifasini bajaradi. Natijada quyidagi jadval shakllantiriladi:
Yuqoridagi modellarni quyidagicha ishlatish mumkin:
using (MobileContext db = new MobileContext())
{
PhoneInfo pi1 = new PhoneInfo { PhoneId = 5, Company = "Samsung", Price = 14000 };
PhoneInfo pi2 = new PhoneInfo { PhoneId = 6, Company = "Nokia", Price = 8000 };
Phone p1 = new Phone { PhoneId = 5, Name = "Samsung Galaxy S5", Info = pi1 };
Phone p2 = new Phone { PhoneId = 6, Name = "Nokia Lumia 630", Info = pi2 };
db.Infos.Add(pi1);
db.Infos.Add(pi2);
db.Phones.Add(p1);
db.Phones.Add(p2);
db.SaveChanges();
foreach (Phone p in db.Phones.Include(p => p.Info))
Console.WriteLine("{0} ({1}) - {2}", p.Name, p.Info.Company, p.Info.Price);
}
Dastur ishga tushirilgach, quyidagi natija ekranga chiqariladi:
Samsung Galaxy S5 (Samsung) - 14000
Nokia Lumia 630 (Nokia) - 8000
Elementlarni bir nechta jadvallarga taqsimlash
Avvalgi mavzuda ikkita klass yagona jadvalga birlashtirilgan edi. Ushbu amalga teskari bo’lgan amalni ham bajarish mumkin. Modelning turli xususiyatlarini turli jadvallarga saqlash mumkin. Modelning muhim xususiyatlarini bitta jadvalga, qo’shimcha xususiyatlarini boshqa jadvalga yozish mumkin:
public class Phone
{
public int Id { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public int Price { get; set; }
}
class MobileContext : DbContext
{
public MobileContext()
: base("DefaultConnection")
{ }
public DbSet Phones { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().Map(m =>
{
m.Properties(d => new { d.Name, d.Id });
m.ToTable("Mobiles");
}).Map(m =>
{
m.Properties(d => new { d.Company, d.Price });
m.ToTable("MobilesInfo");
}); ;
base.OnModelCreating(modelBuilder);
}
}
|