VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Objective-C编程 >
  • LINQ to SQL 之 DataContext

制作者:剑锋冷月 单位:无忧统计网,www.51stat.net
 

  DataContext

  DataContext作为LINQ to SQL框架的主入口点,为我们提供了一些方法和属性,本文用几个例子说明DataContext几个典型的应用。

  创建和删除数据库

  CreateDatabase方法用于在服务器上创建数据库。

  DeleteDatabase方法用于删除由DataContext连接字符串标识的数据库。

  数据库的名称有以下方法来定义:

  如果数据库在连接字符串中标识,则使用该连接字符串的名称。

  如果存在DatabaseAttribute属性(Attribute),则将其Name属性(Property)用作数据库的名称。

  如果连接字符串中没有数据库标记,并且使用强类型的DataContext,则会检查与DataContext继承类名称相同的数据库。如果使用弱类型的DataContext,则会引发异常。

  如果已通过使用文件名创建了DataContext,则会创建与该文件名相对应的数据库。

  我们首先用实体类描述关系数据库表和列的结构的属性。再调用DataContext的CreateDatabase方法,LINQ to SQL会用我们的定义的实体类结构来构造一个新的数据库实例。还可以通过使用 .mdf 文件或只使用目录名(取决于连接字符串),将 CreateDatabase与SQL Server一起使用。LINQ to SQL使用连接字符串来定义要创建的数据库和作为数据库创建位置的服务器。

  说了这么多,用一段实例说明一下吧!

  首先,我们新建一个NewCreateDB类用于创建一个名为NewCreateDB.mdf的新数据库,该数据库有一个Person表,有三个字段,分别为PersonID、PersonName、Age。(点击展开代码)

LINQ体验(16)——LINQ to SQL语句之DataContextLINQ体验(16)——LINQ to SQL语句之DataContext 代码在这里展开public class NewCreateDB : DataContext
{
  public Table<Person> Persons;
  public NewCreateDB(string connection)
    :
    base(connection)
  {
  }
  public NewCreateDB(System.Data.IDbConnection connection)
    :
    base(connection)
  {
  }
}
[Table(Name = "Person")]
public partial class Person : INotifyPropertyChanged
{
  private int _PersonID;
  private string _PersonName;
  private System.Nullable<int> _Age;
  public Person() { }
  [Column(Storage = "_PersonID", DbType = "INT",
    IsPrimaryKey = true)]
  public int PersonID
  {
    get { return this._PersonID; }
    set
    {
      if ((this._PersonID != value))
      {
        this.OnPropertyChanged("PersonID");
        this._PersonID = value;
        this.OnPropertyChanged("PersonID");
      }
    }
  }
  [Column(Storage = "_PersonName", DbType = "NVarChar(30)")]
  public string PersonName
  {
    get { return this._PersonName; }
    set
    {
      if ((this._PersonName != value))
      {
        this.OnPropertyChanged("PersonName");
        this._PersonName = value;
        this.OnPropertyChanged("PersonName");
      }
    }
  }
  [Column(Storage = "_Age", DbType = "INT")]
  public System.Nullable<int> Age
  {
    get { return this._Age; }
    set
    {
      if ((this._Age != value))
      {
        this.OnPropertyChanged("Age");
        this._Age = value;
        this.OnPropertyChanged("Age");
      }
    }
  }
  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged(string PropertyName)
  {
    if ((this.PropertyChanged != null))
    {
      this.PropertyChanged(this,
        new PropertyChangedEventArgs(PropertyName));
    }
  }
}

 

  接下来的一段代码先创建一个数据库,在调用CreateDatabase后,新的数据库就会存在并且会接受一般的查询和命令。接着插入一条记录并且查询。最后删除这个数据库。

//1.新建一个临时文件夹来存放新建的数据库
string userTempFolder = Environment.GetEnvironmentVariable
("SystemDrive") + @"YJingLee";
Directory.CreateDirectory(userTempFolder);
//2.新建数据库NewCreateDB
string userMDF = System.IO.Path.Combine(userTempFolder,
 @"NewCreateDB.mdf");
string connStr = String.Format(@"Data Source=.SQLEXPRESS;
AttachDbFilename={0};Integrated Security=True;
Connect Timeout=30;User Instance=True;
Integrated Security = SSPI;", userMDF);
NewCreateDB newDB = new NewCreateDB(connStr);
newDB.CreateDatabase();
//3.插入数据并查询
var newRow = new Person
{
   PersonID = 1,
   PersonName = "YJingLee",
   Age = 22
};
newDB.Persons.InsertOnSubmit(newRow);
newDB.SubmitChanges();
var q = from x in newDB.Persons
     select x;
//4.删除数据库
newDB.DeleteDatabase();
//5.删除临时目录
Directory.Delete(userTempFolder);
数据库验证

  DatabaseExists方法用于尝试通过使用DataContext中的连接打开数据库,如果成功返回true。

  下面代码说明是否存在Northwind数据库和NewCreateDB数据库 。

//检测Northwind数据库是否存在
if (db.DatabaseExists())
  Console.WriteLine("Northwind数据库存在");
else
  Console.WriteLine("Northwind数据库不存在");
//检测NewCreateDB数据库是否存在
string userTempFolder = Environment.GetEnvironmentVariable("Temp");
string userMDF = System.IO.Path.Combine(userTempFolder,
@"NewCreateDB.mdf");
NewCreateDB newDB = new NewCreateDB(userMDF);
if (newDB.DatabaseExists())
  Console.WriteLine("NewCreateDB数据库存在");
else
  Console.WriteLine("NewCreateDB数据库不存在");
数据库更改

  SubmitChanges方法计算要插入、更新或删除的已修改对象的集,并执行相应命令以实现对数据库的更改。

 

  无论对象做了多少项更改,都只是在更改内存中的副本。并未对数据库中的实际数据做任何更改。直到对DataContext显式调用SubmitChanges,所做的更改才会传输到服务器。调用时,DataContext会设法将我们所做的更改转换为等效的SQL命令。我们也可以使用自己的自定义逻辑来重写这些操作,但提交顺序是由DataContext的一项称作“更改处理器”的服务来协调的。事件的顺序如下:

  当调用SubmitChanges时,LINQ to SQL会检查已知对象的集合以确定新实例是否已附加到它们。如果已附加,这些新实例将添加到被跟踪对象的集合。

  所有具有挂起更改的对象将按照它们之间的依赖关系排序成一个对象序列。如果一个对象的更改依赖于其他对象,则这个对象将排在其依赖项之后。

  在即将传输任何实际更改时,LINQ to SQL会启动一个事务来封装由各条命令组成的系列。

  对对象的更改会逐个转换为SQL命令,然后发送到服务器。

  如果数据库检测到任何错误,都会造成提交进程停止并引发异常。将回滚对数据库的所有更改,就像未进行过提交一样。DataContext 仍具有所有更改的完整记录。

  下面代码说明的是在数据库中查询CustomerID为ALFKI的顾客,然后修改其公司名称,第一次更新并调用SubmitChanges()方法,第二次更新了数据但并未调用SubmitChanges()方法。

//查询
Customer cust = db.Customers.First(c => c.CustomerID == "ALFKI");
//更新数据并调用SubmitChanges()方法
cust.CompanyName = "YJingLee's Blog";
db.SubmitChanges();
//更新数据没有调用SubmitChanges()方法
cust.CompanyName = "http://lyj.cnblogs.com";
动态查询

  使用动态查询,这个例子用CreateQuery()方法创建一个IQueryable<T>类型表达式输出查询的语句。这里给个例子说明一下。有关动态查询具体内容,下一篇介绍。

 

var c1 = Expression.Parameter(typeof(Customer), "c");
PropertyInfo City = typeof(Customer).GetProperty("City");
var pred = Expression.Lambda<Func<Customer, bool>>(
  Expression.Equal(
  Expression.Property(c1, City),
  Expression.Constant("Seattle")
  ), c1
);
IQueryable custs = db.Customers;
Expression expr = Expression.Call(typeof(Queryable), "Where",
  new Type[] { custs.ElementType }, custs.Expression, pred);
IQueryable<Customer> q = db.Customers.AsQueryable().
Provider.CreateQuery<Customer>(expr);
日志

  Log属性用于将SQL查询或命令打印到TextReader。此方法对了解 LINQ to SQL 功能和调试特定的问题可能很有用。

  下面的示例使用Log属性在SQL代码执行前在控制台窗口中显示此代码。我们可以将此属性与查询、插入、更新和删除命令一起使用。

//关闭日志功能
//db.Log = null;
//使用日志功能:日志输出到控制台窗口
db.Log = Console.Out;
var q = from c in db.Customers
    where c.City == "London"
    select c;
//日志输出到文件
StreamWriter sw = new StreamWriter(Server.MapPath("log.txt"), true);
db.Log = sw;
var q = from c in db.Customers
    where c.City == "London"
    select c;
sw.Close();

 

 

  接下来的一段代码先创建一个数据库,在调用CreateDatabase后,新的数据库就会存在并且会接受一般的查询和命令。接着插入一条记录并且查询。最后删除这个数据库。

//1.新建一个临时文件夹来存放新建的数据库
string userTempFolder = Environment.GetEnvironmentVariable
("SystemDrive") + @"YJingLee";
Directory.CreateDirectory(userTempFolder);
//2.新建数据库NewCreateDB
string userMDF = System.IO.Path.Combine(userTempFolder,
 @"NewCreateDB.mdf");
string connStr = String.Format(@"Data Source=.SQLEXPRESS;
AttachDbFilename={0};Integrated Security=True;
Connect Timeout=30;User Instance=True;
Integrated Security = SSPI;", userMDF);
NewCreateDB newDB = new NewCreateDB(connStr);
newDB.CreateDatabase();
//3.插入数据并查询
var newRow = new Person
{
   PersonID = 1,
   PersonName = "YJingLee",
   Age = 22
};
newDB.Persons.InsertOnSubmit(newRow);
newDB.SubmitChanges();
var q = from x in newDB.Persons
     select x;
//4.删除数据库
newDB.DeleteDatabase();
//5.删除临时目录
Directory.Delete(userTempFolder);
数据库验证

  DatabaseExists方法用于尝试通过使用DataContext中的连接打开数据库,如果成功返回true。

  下面代码说明是否存在Northwind数据库和NewCreateDB数据库 。

//检测Northwind数据库是否存在
if (db.DatabaseExists())
  Console.WriteLine("Northwind数据库存在");
else
  Console.WriteLine("Northwind数据库不存在");
//检测NewCreateDB数据库是否存在
string userTempFolder = Environment.GetEnvironmentVariable("Temp");
string userMDF = System.IO.Path.Combine(userTempFolder,
@"NewCreateDB.mdf");
NewCreateDB newDB = new NewCreateDB(userMDF);
if (newDB.DatabaseExists())
  Console.WriteLine("NewCreateDB数据库存在");
else
  Console.WriteLine("NewCreateDB数据库不存在");
数据库更改

  SubmitChanges方法计算要插入、更新或删除的已修改对象的集,并执行相应命令以实现对数据库的更改。



相关教程