Table<TEntity>表示表格记录,它是一个泛型集合类,它的元素就是表格实体对象。它提供一组方法,对元素进行添加删除操作,并可以通过DataContext将这些操作保存到数据库。
表还是前面的那张表,在项目中添加了一个LINQ to SQL类。重点是InsertOnSubmit、DeleteOnSubmit等方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQ_to_SQL_Table
{
/// <summary>
/// 操作单一表格的Table<TEntity>类
/// </summary>
class Program
{
static void Main(string[] args)
{
//1.a.Attach附加实体
DataClasses1DataContext dc1 = new DataClasses1DataContext();
tb_GuestInfo guset = new tb_GuestInfo() { Id=1, Name = "DebugLZQ", Age = 35, Tel = "138****8888" };
dc1.tb_GuestInfo.Attach(guset);//这样的Attach仅仅附加实体,数据库没有更新
dc1.SubmitChanges();
//显示附加成功
foreach (var g in dc1.tb_GuestInfo)
{
Console.WriteLine("{0} {1} {2} {3}", g.Id, g.Name, g.Age, g.Tel);
}
Console.WriteLine("---------");
//显示数据库没有更新
DataClasses1DataContext dc2 = new DataClasses1DataContext();
foreach (var g in dc2.tb_GuestInfo)
{
Console.WriteLine("{0} {1} {2} {3}", g.Id, g.Name, g.Age, g.Tel);
}
Console.WriteLine("------------------------");
Console.ReadKey();
//2.InsertOnSubmit
dc2.tb_GuestInfo.InsertOnSubmit(guset);
dc2.SubmitChanges();
foreach (var g in dc2.tb_GuestInfo)
{
Console.WriteLine("{0} {1} {2} {3}", g.Id, g.Name, g.Age, g.Tel);
}
Console.WriteLine("------------------------");
Console.ReadKey();
//2b.InsertAllOnSubmit 插入集合
List<tb_GuestInfo> lst = new List<tb_GuestInfo>()
{
new tb_GuestInfo(){ Name="AA", Age=25,Tel="133****3333"},
new tb_GuestInfo(){ Name="BB", Age=25,Tel="135****5555"}
};
dc2.tb_GuestInfo.InsertAllOnSubmit(lst);
dc2.SubmitChanges();
foreach (var g in dc2.tb_GuestInfo)
{
Console.WriteLine("{0} {1} {2} {3}", g.Id, g.Name, g.Age, g.Tel);
}
Console.WriteLine("------------------------");
Console.ReadKey();
//
//3.DeleteOnSubmit
tb_GuestInfo entity = (from g in dc2.tb_GuestInfo
where g.Name == "AA"
select g).Single();
dc2.tb_GuestInfo.DeleteOnSubmit(entity);//
dc2.SubmitChanges();
foreach (var g in dc2.tb_GuestInfo)
{
Console.WriteLine("{0} {1} {2} {3}", g.Id, g.Name, g.Age, g.Tel);
}
Console.WriteLine("------------------------");
Console.ReadKey();
//3b.DeleteAllOnSubmit
IEnumerable<tb_GuestInfo> entitys = from g in dc2.tb_GuestInfo
where g.Name == "AA" || g.Name == "BB"
select g;
dc2.tb_GuestInfo.DeleteAllOnSubmit(entitys);
dc2.SubmitChanges();
foreach (var g in dc2.tb_GuestInfo)
{
Console.WriteLine("{0} {1} {2} {3}", g.Id, g.Name, g.Age, g.Tel);
}
Console.WriteLine("------------------------");
Console.ReadKey();
}
}
}
程序运行结果如下: