您好,登錄后才能下訂單哦!
這篇文章主要介紹如何創(chuàng)建Linq數(shù)據(jù)庫,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
創(chuàng)建Linq數(shù)據(jù)庫
◆CreateDatabase方法用于在服務(wù)器上創(chuàng)建Linq數(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)建與該文件名相對應(yīng)的數(shù)據(jù)庫。
我們首先用實體類描述關(guān)系數(shù)據(jù)庫表和列的結(jié)構(gòu)的屬性。再調(diào)用DataContext的 CreateDatabase方法,LINQ to SQL會用我們的定義的實體類結(jié)構(gòu)來構(gòu)造一個新的數(shù)據(jù)庫實例。還可以通過使用 .mdf 文件或只使用目錄名(取決于連接字符串),將 CreateDatabase與SQL Server一起使用。LINQ to SQL使用連接字符串來定義要創(chuàng)建Linq數(shù)據(jù)庫和作為數(shù)據(jù)庫創(chuàng)建位置的服務(wù)器。
說了這么多,用一段實例說明一下吧!
首先,我們新建一個NewCreateDB類用于創(chuàng)建一個名為NewCreateDB.mdf的新數(shù)據(jù)庫,該數(shù)據(jù)庫有一個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)); } } }
一段代碼先創(chuàng)建Linq數(shù)據(jù)庫,在調(diào)用CreateDatabase后,新的數(shù)據(jù)庫就會存在并且會接受一般的查詢和命令。接著插入一條記錄并且查詢。***刪除這個數(shù)據(jù)庫。
以上是“如何創(chuàng)建Linq數(shù)據(jù)庫”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。