|
Yangi yozuv qo’shish va chiqarish
|
bet | 24/53 | Sana | 30.11.2023 | Hajmi | 1,39 Mb. | | #108476 |
Bog'liq Dasturiy injiniringYangi yozuv qo’shish va chiqarish
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Entity;
namespace ManyToMany
{
class Program
{
static void Main(string[] args)
{
using (SoccerContext db = new SoccerContext())
{
// Yangi model yaratish va qo’shish
Player pl1 = new Player { Name = "Ronaldu", Age = 31, Position = "Hujumchi" };
Player pl2 = new Player { Name = "Messi", Age = 28, Position = "Hujumchi" };
Player pl3 = new Player { Name = "Xavi", Age = 34, Position = "Yarim himoyachi" };
db.Players.AddRange(new List { pl1, pl2, pl3 });
db.SaveChanges();
Team t1 = new Team { Name = "Barselona" };
t1.Players.Add(pl2);
t1.Players.Add(pl3);
Team t2 = new Team { Name = "Real Madrid" };
t2.Players.Add(pl1);
db.Teams.Add(t1);
db.Teams.Add(t2);
db.SaveChanges();
foreach (Team t in db.Teams.Include(t => t.Players))
{
Console.WriteLine("Jamoa: {0}", t.Name);
foreach (Player pl in t.Players)
{
Console.WriteLine("{0} - {1}", pl.Name, pl.Position);
}
Console.WriteLine();
}
}
}
}
}
Ro’yxatda bitta modelni boshqasiga qo’shishda ushbu ro’yxat shakllangan bo’lishi shart. Aks holda xatolik qaytariladi. Ushbu holda har ikkala modellar konstruktorida ro'yxat shakllantirilgan.
O’zgartirish
// Bitta obyekt bilan aloqani o’chiramiz
Player pl_edit = db.Players.First(p => p.Name == "Messi");
Team t_edit = pl_edit.Teams.First(p => p.Name == "Barselona");
t_edit.Players.Remove(pl_edit);
Komandadan biror futbolchini o’chirish natijasida TeamPlayers jadvalidagi futbolchi Id si va komanda Id siga mos yozuvning o’chirilishiga olib keladi. Futbolchini DBdan o’chirish esa futbolchi Id siga mos bo’lgan TeamPlayers dagi barcha yozuvlarning o’chirilishiga olib keladi.
Player pl_delete = db.Players.First(p => p.Name == "Messi");
db.Players.Remove(pl_delete);
Ko’pga-ko’p aloqa.Misol
Windows Forms tipiga mansub yangi loyihani hosil qilamiz va unga ushbu modellarni qo’shib qo’yamiz. So’ngra, NuGet orqali Entity Framework paketini va mos ma’lumotlar kontekstini hosil qilamiz:
class SoccerContext : DbContext
{
public SoccerContext()
: base("SoccerDB2")
{ }
public DbSet Teams { get; set; }
public DbSet Players { get; set; }
}
Modellar:
class Team
{
public int Id { get; set; }
public string Name { get; set; }
public string Coach { get; set; }
public virtual ICollection Players { get; set; }
public Team()
{
Players = new List();
}
}
class Player
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public virtual ICollection Teams { get; set; }
public Player()
{
Teams = new List();
}
}
Endi asosiy dasturni shakllantiramiz. Asosiy formada jalval shaklida futbolchilar ro'yxati shakllantiriladi:
Ushbu formadagi funksional avvalgi misoldagi kabi amalga oshiriladi:bitta DataGridView va to’rtta tugma. Shuningdek, ikkita qo’shimcha formalar zarur: bittasi yangi jamoani hosil qilish uchun, ikkinchisi – futbolchini qo’shish/o’zgartirish uchun.
Loyihamizga yangi formani qo’shamiz. Unga PlayerForm nomini beramiz:
Bu yerda matnli maydonda futbolchining FIOsi, maydoni NumericUpDown futbolchi yoshi uchun, ListBox elementida esa jamoalar ro'yxati namoyish qilinadi. Formadagi barcha elementlarning Modifier xususiyatini Protected Internal ga tenglashtiramiz.
Shuningdek ushbu formada ikkita tugma mavjud. 'OK' tugmasining DialogResult xususiyati qiymatini OK ga, 'Otmena' tugmasining DialogResult xususiyati qiymatini Cancel ga tenglashtiramiz.
Yangi jamoani qo’shish formasini TeamForm deb nomlaymiz va u quyidagi ko’rinishga ega:
Ushbu formadagi elementlarning xususiyatlari qiymatlarini yuqoridagi futbolchiga mos forma elementlariga o’xshash tarzda o’zgartiramiz. So’ngra bosh formadagi o'yinchilar ro'yxatini chiqaruvchi kodni shakllantiramiz:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ManyToManyApp
{
public partial class Form1 : Form
{
SoccerContext db;
public Form1()
{
InitializeComponent();
db = new SoccerContext();
db.Players.Load();
dataGridView1.DataSource = db.Players.Local.ToBindingList();
}
private void button1_Click(object sender, EventArgs e)
{
PlayerForm plForm = new PlayerForm();
// plForm formaga buyruqlar ro’yxatini ochish
List teams = db.Teams.ToList();
plForm.listBox1.DataSource = teams;
plForm.listBox1.ValueMember = "Id";
plForm.listBox1.DisplayMember = "Name";
DialogResult result = plForm.ShowDialog(this);
if (result == DialogResult.Cancel)
return;
Player player = new Player();
player.Age = (int)plForm.numericUpDown1.Value;
player.Name = plForm.textBox1.Text;
teams.Clear(); // ro’yxat tozalanadi va uni qaytadan ma’lumotlar bilan //to’ldirib chiqiladi
foreach (var item in plForm.listBox1.SelectedItems)
{
teams.Add((Team)item);
}
player.Teams = teams;
db.Players.Add(player);
db.SaveChanges();
MessageBox.Show("Yangi futbolchi qo’shildi");
}
private void button4_Click(object sender, EventArgs e)
{
TeamForm tmForm = new TeamForm();
DialogResult result = tmForm.ShowDialog(this);
if (result == DialogResult.Cancel)
return;
Team team = new Team();
team.Name = tmForm.textBox1.Text;
team.Coach = tmForm.textBox2.Text;
team.Players = new List();
db.Teams.Add(team);
db.SaveChanges();
MessageBox.Show("Yangi jamoa qo’shildi");
}
private void button2_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count < 1)
return;
int index = dataGridView1.SelectedRows[0].Index;
int id = 0;
bool converted = Int32.TryParse(dataGridView1[0, index].Value.ToString(), out id);
if (converted == false)
return;
Player player = db.Players.Find(id);
PlayerForm plForm = new PlayerForm();
plForm.numericUpDown1.Value = player.Age;
plForm.textBox1.Text = player.Name;
// komanda ro’yxatini olish
List teams = db.Teams.ToList();
plForm.listBox1.DataSource = teams;
plForm.listBox1.ValueMember = "Id";
plForm.listBox1.DisplayMember = "Name";
foreach (Team t in player.Teams)
plForm.listBox1.SelectedItem = t;
DialogResult result = plForm.ShowDialog(this);
if (result == DialogResult.Cancel)
return;
player.Age = (int)plForm.numericUpDown1.Value;
player.Name = plForm.textBox1.Text;
// Futbolchining komandasi mavjudligini aniqlaymiz
foreach (var team in teams)
{
if (plForm.listBox1.SelectedItems.Contains(team))
{
if (!player.Teams.Contains(team))
player.Teams.Add(team);
}
else
{
if (player.Teams.Contains(team))
player.Teams.Remove(team);
}
}
db.Entry(player).State = EntityState.Modified;
db.SaveChanges();
MessageBox.Show("Ma’lumot yangilandi");
}
private void button3_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count < 1)
return;
int index = dataGridView1.SelectedRows[0].Index;
int id = 0;
bool converted = Int32.TryParse(dataGridView1[0, index].Value.ToString(), out id);
if (converted == false)
return;
Player player = db.Players.Find(id);
db.Players.Remove(player);
db.SaveChanges();
MessageBox.Show("Futbolchi o’chirildi");
}
}
}
Ma’lumotlar bazasini initsializatsiya qilish
Agar DBga birinchi marotaba murojaat qilinganda, DBni boshlang‘ich ma’lumotlar bilan to’ldirish lozim bo’lsa, initsializatsiyani amalga oshirishimiz mumkin.
Initsializatsiya ma’lumotlar kontekstiga birinchi marotaba murojaat qilinganda amalga oshiriladi. Initsializatsiya uchun .NET bibliotekasida mavjud quyidagi klasslardan foydalanishimiz mumkin:
• CreateDatabaseIfNotExists: boshlang‘ich holda ishlatiladigan initsializator. U DB dagi ma’lumotlarni avtomatik o’chirmaydi. Agar model va ma’lumotlar kontekstini tuzilmasi o’zgartirilgan vaqtda xatolikni qaytaradi.
• DropCreateDatabaseWhenModelChanges: ushbu initsializator model va DB jadvallari mosligini aniqlaydi. Agar modelda jadvalga moslik mavjud bo’lmasa, DB qayta yaratiladi.
• DropCreateDatabaseAlways: Ushbu initsializator orqali DB qayta shakllantiriladi
Ushbu initsializatorlarning biridan foydalanish lozim. Buning uchun bizga Seed metodi xizmat qiladi:
|
| |