Ngôn ngữ LINQ - Thao tác xóa dữ liệu
Thao tác xóa dữ liệu
Đoạn mã sau xóa một tác giả ra khỏi cơ sở dữ liệu:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoLinq
{
class Program
{
static void Main(string[] args)
{
using (var dataBook = new DataBookStoreDataContext())
{
//Xóa tác giá có id=10 là Thích Học Lại
Author author = dataBook.Authors.Single(a => a.AuthorID == 10);
dataBook.Authors.DeleteOnSubmit(author);
try
{
dataBook.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
// Make some adjustments.
// ...
// Try again.
dataBook.SubmitChanges();
}
}
}
}
}
Kết quả:
Ví dụ này thực hiện việc delete
một đối tượng có trong author. Cũng như update
và insert
sau khi dòng code dataBook.Authors.DeleteOnSubmit(author);
được thực thi thì mới chỉ xóa được trên đối tượng trên DBMemberDataContext
. Ta có 10 dòng dữ liệu giờ còn 9 dòng
Vì vậy dùng dataBook.SubmitChanges();
để cập nhật lại dữ liệu trên SQL Server.