簡單實現(xiàn)linq創(chuàng)建數(shù)據(jù)庫
如何實現(xiàn)linq創(chuàng)建數(shù)據(jù)庫呢?本文筆者將結合理論與實際,為大家講些linq創(chuàng)建數(shù)據(jù)庫的方法,希望能給你帶來幫助。
◆CreateDatabase方法用于在服務器上實現(xiàn)linq創(chuàng)建數(shù)據(jù)庫。
◆DeleteDatabase方法用于刪除由DataContext連接字符串標識的數(shù)據(jù)庫。
數(shù)據(jù)庫的名稱有以下方法來定義:
◆如果數(shù)據(jù)庫在連接字符串中標識,則使用該連接字符串的名稱。
◆如果存在DatabaseAttribute屬性(Attribute),則將其Name屬性(Property)用作數(shù)據(jù)庫的名稱。
◆如果連接字符串中沒有數(shù)據(jù)庫標記,并且使用強類型的DataContext,則會檢查與DataContext繼承類名稱相同的數(shù)據(jù)庫。如果使用弱類型的DataContext,則會引發(fā)異常。
如果已通過使用文件名創(chuàng)建了DataContext,則會創(chuàng)建與該文件名相對應的數(shù)據(jù)庫。
我們首先用實體類描述關系數(shù)據(jù)庫表和列的結構的屬性。再調用DataContext的 CreateDatabase方法,LINQ to SQL會用我們的定義的實體類結構來構造一個新的數(shù)據(jù)庫實例。還可以通過使用 .mdf 文件或只使用目錄名(取決于連接字符串),將 CreateDatabase與SQL Server一起使用。LINQ to SQL使用連接字符串來定義要實現(xiàn)linq創(chuàng)建數(shù)據(jù)庫和作為數(shù)據(jù)庫創(chuàng)建位置的服務器。
說了這么多,用一段實例說明一下吧!
首先,我們新建一個NewCreateDB類用于創(chuàng)建一個名為NewCreateDB.mdf的新數(shù)據(jù)庫,該數(shù)據(jù)庫有一個Person表,有三個字段,分別為PersonID、PersonName、Age。
- public class NewCreateDB : DataContext
- {
- public Table
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));
- }
- }
- }
一段代碼先實現(xiàn)linq創(chuàng)建數(shù)據(jù)庫,在調用CreateDatabase后,新的數(shù)據(jù)庫就會存在并且會接受一般的查詢和命令。接著插入一條記錄并且查詢。***刪除這個數(shù)據(jù)庫。
【編輯推薦】