首页 / 软件开发 / LINQ / LINQ to SQL语句(22)之DataContext
LINQ to SQL语句(22)之DataContext2010-12-11 博客园 李永京DataContextDataContext作为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。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));
}
}
}