|
Dasturiy injiniring (EntityFramework 6)
|
bet | 34/53 | Sana | 30.11.2023 | Hajmi | 1,39 Mb. | | #108476 |
Bog'liq Dasturiy injiniringCompanies jadvaldagi barcha modellarni olamiz:
static void Main(string[] args)
{
using (PhoneContext db = new PhoneContext())
{
var comps = db.Database.SqlQuery("SELECT * FROM Companies");
foreach (var company in comps)
Console.WriteLine(company.Name);
}
Console.ReadLine();
}
SELECT ifodasi orqali jadvaldagi ma’lumotlar olinadi. Yuqoridagi misolda ushbu jadval Company modeliga mos qo’yilgan bo’lib, ushbu modelga mos bo’lgan ob’ektlarni o’zida saqlaydi va ushbu chaqiruv Company klassi orqali tiplashtiriladi db.Database.SqlQuery().
SqlQuery() metodining boshqa versiyasi parametrlarni ishlatishni ta'minlaydi. Masalan, DBdan "Samsung" satrini o’zida saqlovchi barcha modellarni tanlash lozim bo’lsin:
using (PhoneContext db = new PhoneContext())
{
System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter("@name", "%Samsung%");
var phones = db.Database.SqlQuery("SELECT * FROM Phones WHERE Name LIKE @name", param);
foreach (var phone in phones)
Console.WriteLine(phone.Name);
}
System.Data.SqlClient nomlar fazosidagi SqlParameter klassi orqali sql so’rovda ishlatiladigan parametrni uzatish mumkin.
SqlQuery() metodi orqali DBdan tanlash amali bajariladi. Ammo ba’zi hollarda DBda o’chirish, yangilash va yangi yozuv qo’shish kabi amallarni bajarishimizga to’g‘ri keladi. Ushbu maqsadda ExecuteSqlCommand() metodidan foydalaniladi. Ushbu metodni quyidagicha qo’llashimiz mumkin:
using (PhoneContext db = new PhoneContext())
{
// yangi yozuv
int numberOfRowInserted = db.Database.ExecuteSqlCommand("INSERT INTO Companies (Name) VALUES ('HTC')");
// o’zgartirish
int numberOfRowUpdated = db.Database.ExecuteSqlCommand("UPDATE Companies SET Name='Nokia' WHERE Id=3");
// o’chirish
int numberOfRowDeleted = db.Database.ExecuteSqlCommand("DELETE FROM Companies WHERE Id=3");
}
Foydalanuvchi funksiyalari
|
| |