例子:Database - Linq to sql

时间:2022-07-27 06:32:15
DataContext类型(数据上下文)是System.Data.Linq命名空间下的重要类型,用于把查询句法翻译成SQL语句,以及把数据从数据库返回给调用方和把实体的修改写入数据库。
  • DataContext提供了以下一些使用的功能:
  • 以日志形式记录DataContext生成的SQL
  • 执行SQL(包括查询和更新语句)
  • 创建和删除数据库

DataContext 是通过数据库连接映射的所有实体的源。 它会跟踪您对所有检索到的实体所做的更改,并且保留一个“标识缓存”,该缓存确保使用同一对象实例表示多次检索到的实体。

通常情况下,DataContext 实例设计为持续一个“工作单位”,但您的应用程序可以定义该持续周期。 DataContext 是轻量的,创建它不需要很大的开销。 典型的 LINQ to SQL 应用程序在方法范围内创建 DataContext 实例,或将这些实例创建为生存期较短的类(这些类表示相关数据库操作的逻辑集合)的成员。

1. 创建数据库表对应实例

        [Table]
public class Employee
{
[Column(IsPrimaryKey = true)]
public int EmployeeID
{
get;
set;
}
[Column(CanBeNull = false)]
public string EmployeeName
{
get;
set;
}
[Column(CanBeNull = false)]
public string EmployeeAge
{
get;
set;
}
}

2. 对DdataContext做个简单封装

    public class EmployeeDataContext : DataContext
{
public EmployeeDataContext(string connectionString)
: base(connectionString)
{
}
public Table<Employee> Employees
{
get
{
return this.GetTable<Employee>();
}
}
}

private const string strConnectionString = @"isostore:/EmployeeDB.sdf";

3. 创建数据库

            using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
if (Empdb.DatabaseExists() == false)
{
Empdb.CreateDatabase();
}

4. 添加一条记录

private const string strConnectionString = @"isostore:/EmployeeDB.sdf";

using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
Employee newEmployee = new Employee
{
EmployeeID = Convert.ToInt32(txtEmpid.Text),
EmployeeAge = txtAge.Text.ToString(),
EmployeeName = txtName.Text.ToString()
}; Empdb.Employees.InsertOnSubmit(newEmployee);
Empdb.SubmitChanges();

5. 查找一条记录

            using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees where Emp.EmployeeName == txtName.Text select Emp;
Employee EmpRemove = EmpQuery.FirstOrDefault();
Empdb.Employees.DeleteOnSubmit(EmpRemove);
Empdb.SubmitChanges();
MessageBox.Show("Employee Deleted Successfully!!!");
}

6. 删除数据库

            using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
if (Empdb.DatabaseExists())
{
Empdb.DeleteDatabase(); }
}