Bài 10-Thêm dữ liệu vào MongoDB trong C#-WPF

CRUD là một thuật ngữ nói về các thao tác: Thêm, Xem, Sửa Xóa.

C (Create->Insert dữ liệu mới)

R (Retrieve -> Select truy vấn dữ liệu)

U (Update -> Cập nhật dữ liệu)

D (Delete -> Xóa dữ liệu)

Bất kỳ một phần mềm quản lý nào cũng phải có tối thiểu cung cấp được CRUD cho người dùng tương tác.

Kết thúc bài hướng dẫn này bạn phải làm được chức năng Lưu dữ liệu, chức năng Xem ta đã làm ở các bài học trước rồi. Kết quả bạn phải làm được giao diện và tương tác dữ liệu như màn hình dưới đây:

– Chức năng hiển thị toàn bộ Product trong cơ sơ dữ liệu MongoDB lên giao diện các bạn tự xem lại các bài học:

Bài 5-Kết nối và truy vấn dữ liệu MongoDB bằng C#

Bài 6-Kỹ thuật Truy vấn với dữ liệu lớn trong MongoDB

Bài 7 – Các Kỹ thuật filter dữ liệu trong MongoDB với C#

Bài 8 – Kỹ thuật Binding dữ liệu MongoDB lên ListView WPF

Bài 9- Kỹ thuật sắp xếp dữ liệu MongoDB bằng C#

– Chức năng thêm mới dữ liệu:

Khi bấm vào nút Thêm sẽ mở ra màn hình mới để người dùng cung cấp: Mã , tên, đơn giá. Khi bấm lưu sẽ lưu dữ liệu này vào MongoDB.

Với MongoDB thì mỗi một dữ liệu chúng ta đẩy vào chính là 1 BsonDocument (trong SQL Server gọi là record). Bạn có thể so sánh tham chiếu từ Cơ sở dữ liệu quan hệ qua NoSQL như sau:

Tui giải thích sơ qua: Ở Cơ sở dữ liệu quan hệ ta có 2 bảng Person và Car. Mỗi bảng có dòng và cột. Thì nó sẽ mapping qua BSon: 1 Person có nhiều Car nên ta có 1 JSonObject ở ngoài và ở bên trong là JSonArray (cars).

Dưới đây là hình mô tả sự khác biệt giữa JSon và Bson. Json Tui có giải thích sơ bộ ở bài này.

Để lưu dữ liệu vào MongoDB thì bước trước tiên ta phải tạo 1 đối tượng là BSonDocument:

[code language=”csharp”]

private void btnLuu_Click(object sender, RoutedEventArgs e)
{
MongoClient client = new MongoClient(“mongodb://localhost:27017”);
IMongoDatabase database = client.GetDatabase(“QuanLySanPham”);
IMongoCollection collection = database.GetCollection(“Product”);
BsonDocument document = new BsonDocument
{
{ “Ma”,”P8″},
{ “Ten”,”Thuốc trị hôi nách”},
{ “DonGia”,19.5},
};
collection.InsertOne(document);
MessageBox.Show(“Đã lưu thành công”);
}

[/code]

Ta thấy Tui khai báo 1 BsonDocument, tạo các thuộc tính: Ma, Ten, DonGia (3 thuộc tính này phải so khớp chính xác trong bảng Product của MongoDB).

Sau đó gọi lệnh InsertOne(document) ==> lưu vào Cơ sở dữ liệu.

Lưu ý nó còn vài cách lưu khác nữa, ta chưa bàn ở chỗ này.

Bây giờ ta tạo 1 Project tên là “CRUD_MongoCSharp“, rồi tiến hành tạo giao diện và xử lý nghiệp vụ như hướng dẫn chi tiết dưới này:

Chi tiết XAML cho giao diện chính: (MainWindow.xaml):

[code language=”xml”]

[/code]

Coding model cho bảng Product:

[code language=”csharp”]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRUD_MongoCSharp
{
public class Product
{
public object _id { get; set; }
public string Ma { get; set; }
public string Ten { get; set; }
public double DonGia { get; set; }
}
}

[/code]

Chi tiết coding MainWindow.xaml.cs:

[code language=”java”]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MongoDB;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
namespace CRUD_MongoCSharp
{
///

/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
LoadAllProduct();
}
private void LoadAllProduct()
{
MongoClient client = new MongoClient(“mongodb://localhost:27017”);
IMongoDatabase database = client.GetDatabase(“QuanLySanPham”);
IMongoCollection collection = database.GetCollection(“Product”);
List documents = collection.Find(new BsonDocument()).ToList();
List dsProduct = new List();
foreach(BsonDocument document in documents)
{
Product p = BsonSerializer.Deserialize(document);
dsProduct.Add(p);
}
lvProduct.ItemsSource = dsProduct;
}

private void btnThem_Click(object sender, RoutedEventArgs e)
{
ThemSanPham frm = new ThemSanPham();
frm.ShowDialog();
}

private void btnXem_Click(object sender, RoutedEventArgs e)
{
LoadAllProduct();
}
}
}

[/code]

Giao diện ThemSanPham.xaml:

[code language=”xml”]

[/code]

Coding màn hình Thêm dữ liệu (ThemSanPham.xaml.cs):

[code language=”csharp”]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MongoDB;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
namespace CRUD_MongoCSharp
{
///

/// Interaction logic for ThemSanPham.xaml
///

public partial class ThemSanPham : Window
{
public ThemSanPham()
{
InitializeComponent();
}

private void btnDong_Click(object sender, RoutedEventArgs e)
{
Close();
}

private void btnTiep_Click(object sender, RoutedEventArgs e)
{
txtMa.Clear();
txtTen.Clear();
txtDonGia.Clear();
txtMa.Focus();
}
private void btnLuu_Click(object sender, RoutedEventArgs e)
{
MongoClient client = new MongoClient(“mongodb://localhost:27017”);
IMongoDatabase database = client.GetDatabase(“QuanLySanPham”);
IMongoCollection collection = database.GetCollection(“Product”);
BsonDocument document = new BsonDocument
{
{ “Ma”,txtMa.Text},
{ “Ten”,txtTen.Text},
{ “DonGia”,txtDonGia.Text},
};
collection.InsertOne(document);
MessageBox.Show(“Đã lưu thành công”);
}
}
}

[/code]

Chạy chương trình lên ta có được kết quả như mong muốn.

Các bạn có thể tải source code đầy đủ ở đây: Source code thêm Sản phẩm

Bài học Sau Tui sẽ hướng dẫn các bạn các kỹ thuật tương tác dữ liệu (sửa, xóa), các bạn chú ý theo dõi.

Các khóa học online khác, bạn có thể tham khảo tại đây:

https://unica.vn/?aff=11929

Chúc các bạn thành công!

4 thoughts on “Bài 10-Thêm dữ liệu vào MongoDB trong C#-WPF”

Leave a Reply