Linq to Entities da so’rovlarni amalga oshirish uchun, Linq to Objects kabi LINQ operatorlarini va LINQ kengaytirma metodlarini qo’llashimiz mumkin. LINQ ning ba’zi operatorlarini ishlatishga misol:
using (PhoneContext db = new PhoneContext())
{
var phones = from p in db.Phones
where p.CompanyId == 1
select p;
}
Xuddi shu so’rovni LINQ kengaytirma metodlari orqali amalga oshirish mumkin:
using (PhoneContext db = new PhoneContext())
{
var phones = db.Phones.Where(p => p.CompanyId == 1);
}
Dastur kodi:
static void Main(string[] args)
{
using (PhoneContext db = new PhoneContext())
{
var phones = from p in db.Phones
where p.CompanyId == 1
select p;
foreach (Phone p in phones)
Console.WriteLine("{0}.{1} - {2}", p.Id, p.Name, p.Price);
Console.ReadLine();
}
using (PhoneContext db = new PhoneContext())
{
var phones = db.Phones.Where(p => p.CompanyId == 1);
foreach (Phone p in phones)
Console.WriteLine("{0}.{1} - {2}", p.Id, p.Name, p.Price);
Console.ReadLine();
}
}
Har ikkala so’rovlar bir xil sql ifodani generatsiya qiladi:
SELECT [Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[Price] AS [Price],
[Extent1].[CompanyId] AS [CompanyId]
FROM [dbo].[Phones] AS [Extent1]
WHERE 1 = [Extent1].[CompanyId]
Linq to Entities va Linq to Objects ning farqini bilish kerak:
var phones = db.Phones.Where(p => p.CompanyId == 1).ToList().Where(p => p.Id < 10);
Bu yerda ikkita Where metodi ishlatilgan bo’lib, ularning qo’llanilishi ikki xil:
db.Phones.Where(p=> p.CompanyId == 1)
ifoda orqali SQL ifoda translyatsiya qilinadi. So’ngra ToList() metodi so’rov natijasiga ko’ra xotirada ro'yxatni shakllantiradi.
Keyingi qadamda biz xotiradagi ro'yxatga ega bo’lamiz. So’ngra, Where(p=> p.Id<10) jamoasi orqali xotiradagi ro'yxatga murojaat qilamiz ва Linq to Object dan foydalanamiz.
Endi LINQ ni DBdan olingan ma’lumotlarga qo’llashni ko’rib chiqamiz.
Ma’lumotlar bazasidan shart asosida tanlash va proeksiya
DBdan shart asosida tanlash uchun Where metodidan foydalanish lozim. DBda ishlab chiqarilgan tashkiloti "Samsung" bo’lgan barcha telefonlarni aniqlash lozim bo’lsin:
using (PhoneContext db = new PhoneContext())
{
var phones = db.Phones.Where(p => p.Company.Name == "Samsung");
foreach (Phone p in phones)
Console.WriteLine("{0}.{1} - {2}", p.Id, p.Name, p.Price);
}
|