創(chuàng)建Linq數(shù)據(jù)庫簡單描述
本文向大家介紹創(chuàng)建Linq數(shù)據(jù)庫,可能好多人還不了解創(chuàng)建Linq數(shù)據(jù)庫,沒有關(guān)系,看完本文你肯定有不少收獲,希望本文能教會(huì)你更多東西。
創(chuàng)建Linq數(shù)據(jù)庫
◆CreateDatabase方法用于在服務(wù)器上創(chuàng)建Linq數(shù)據(jù)庫。
◆DeleteDatabase方法用于刪除由DataContext連接字符串標(biāo)識(shí)的數(shù)據(jù)庫。
數(shù)據(jù)庫的名稱有以下方法來定義:
◆如果數(shù)據(jù)庫在連接字符串中標(biāo)識(shí),則使用該連接字符串的名稱。
◆如果存在DatabaseAttribute屬性(Attribute),則將其Name屬性(Property)用作數(shù)據(jù)庫的名稱。
◆如果連接字符串中沒有數(shù)據(jù)庫標(biāo)記,并且使用強(qiáng)類型的DataContext,則會(huì)檢查與DataContext繼承類名稱相同的數(shù)據(jù)庫。如果使用弱類型的DataContext,則會(huì)引發(fā)異常。
如果已通過使用文件名創(chuàng)建了DataContext,則會(huì)創(chuàng)建與該文件名相對應(yīng)的數(shù)據(jù)庫。
我們首先用實(shí)體類描述關(guān)系數(shù)據(jù)庫表和列的結(jié)構(gòu)的屬性。再調(diào)用DataContext的 CreateDatabase方法,LINQ to SQL會(huì)用我們的定義的實(shí)體類結(jié)構(gòu)來構(gòu)造一個(gè)新的數(shù)據(jù)庫實(shí)例。還可以通過使用 .mdf 文件或只使用目錄名(取決于連接字符串),將 CreateDatabase與SQL Server一起使用。LINQ to SQL使用連接字符串來定義要?jiǎng)?chuàng)建Linq數(shù)據(jù)庫和作為數(shù)據(jù)庫創(chuàng)建位置的服務(wù)器。
說了這么多,用一段實(shí)例說明一下吧!
首先,我們新建一個(gè)NewCreateDB類用于創(chuàng)建一個(gè)名為NewCreateDB.mdf的新數(shù)據(jù)庫,該數(shù)據(jù)庫有一個(gè)Person表,有三個(gè)字段,分別為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));
- }
- }
- }
一段代碼先創(chuàng)建Linq數(shù)據(jù)庫,在調(diào)用CreateDatabase后,新的數(shù)據(jù)庫就會(huì)存在并且會(huì)接受一般的查詢和命令。接著插入一條記錄并且查詢。***刪除這個(gè)數(shù)據(jù)庫。
【編輯推薦】