天天看点

SQL Metal在生成Windows Phone数据库

如果在winsows phone中使用数据库,可以使用SQLMetal,它不但能把SQL Server中的数据生成实体应用在WP中,还可以很方便的使用Linq来对数据库各实体进行操作。可以说是手机开发与桌面及web开发实现无缝的开发体验。

<b>1、 </b><b>创建</b><b>SQL</b><b>数据库</b>

<a href="http://blog.51cto.com/attachment/201201/175307324.png" target="_blank"></a>

<b>2、 </b><b>把</b><b>SQL</b><b>库导成实体</b><b>CSharp</b><b>源代码</b>

安装完WP开发环境后,会在安装路径下安装一个工具sqletal,这个工具可以帮助我们把SQL Server数据库转换成WP中应用的CSharp源代码。

在cmd命令下键入:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin&gt;sqlmetal /server:. /database:accou

nt_db /namespace:test /code:f:/test.cs /language:csharp

server:指sql server服务器名

database:数据库名

namespace:生成的命名空间

code:生成源代码的路径和文件名

language:生成的语言

生成的源码如下:

#pragma warning disable 1591  

namespace test  

{  

         using System.Data.Linq;  

         using System.Data.Linq.Mapping;  

         using System.Data;  

         using System.Collections.Generic;  

         using System.Reflection;  

         using System.Linq;  

         using System.Linq.Expressions;  

         using System.ComponentModel;  

         using System;  

         [System.Data.Linq.Mapping.DatabaseAttribute(Name="account_db")]  

         public partial class Account_db : System.Data.Linq.DataContext  

         {  

                   private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();  

    #region Extensibility Method Definitions  

    partial void OnCreated();  

    partial void InsertAccounts(Accounts instance);  

    partial void UpdateAccounts(Accounts instance);  

    partial void DeleteAccounts(Accounts instance);  

    partial void InsertItems(Items instance);  

    partial void UpdateItems(Items instance);  

    partial void DeleteItems(Items instance);  

    #endregion  

                   public Account_db(string connection) :   

                                     base(connection, mappingSource)  

                   {  

                            OnCreated();  

                   }  

                   public Account_db(System.Data.IDbConnection connection) :   

                   public Account_db(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :   

                   public Account_db(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :   

                   public System.Data.Linq.Table&lt;Accounts&gt; Accounts  

                            get 

                            {  

                                     return this.GetTable&lt;Accounts&gt;();  

                            }  

                   public System.Data.Linq.Table&lt;Items&gt; Items  

                                     return this.GetTable&lt;Items&gt;();  

         }  

         [Table(Name="dbo.Accounts")]  

         public partial class Accounts : INotifyPropertyChanging, INotifyPropertyChanged  

                   private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);  

                   private int _ID;  

                   private System.Nullable&lt;decimal&gt; _Amount;  

                   private System.Nullable&lt;System.DateTime&gt; _Dtime;  

                   private System.Nullable&lt;int&gt; _ItemID;  

                   private EntityRef&lt;Items&gt; _Items;  

    partial void OnLoaded();  

    partial void OnValidate(System.Data.Linq.ChangeAction action);  

    partial void OnIDChanging(int value);  

    partial void OnIDChanged();  

    partial void OnAmountChanging(System.Nullable&lt;decimal&gt; value);  

    partial void OnAmountChanged();  

    partial void OnDtimeChanging(System.Nullable&lt;System.DateTime&gt; value);  

    partial void OnDtimeChanged();  

    partial void OnItemIDChanging(System.Nullable&lt;int&gt; value);  

    partial void OnItemIDChanged();  

                   public Accounts()  

                            this._Items = default(EntityRef&lt;Items&gt;);  

                   [Column(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]  

                   public int ID  

                                     return this._ID;  

                            set 

                                     if ((this._ID != value))  

                                     {  

                                               this.OnIDChanging(value);  

                                               this.SendPropertyChanging();  

                                               this._ID = value;  

                                               this.SendPropertyChanged("ID");  

                                               this.OnIDChanged();  

                                     }  

                   [Column(Storage="_Amount", DbType="Money")]  

                   public System.Nullable&lt;decimal&gt; Amount  

                                     return this._Amount;  

                                     if ((this._Amount != value))  

                                               this.OnAmountChanging(value);  

                                               this._Amount = value;  

                                               this.SendPropertyChanged("Amount");  

                                               this.OnAmountChanged();  

                   [Column(Storage="_Dtime", DbType="DateTime")]  

                   public System.Nullable&lt;System.DateTime&gt; Dtime  

                                     return this._Dtime;  

                                     if ((this._Dtime != value))  

                                               this.OnDtimeChanging(value);  

                                               this._Dtime = value;  

                                               this.SendPropertyChanged("Dtime");  

                                               this.OnDtimeChanged();  

                   [Column(Storage="_ItemID", DbType="Int")]  

                   public System.Nullable&lt;int&gt; ItemID  

                                     return this._ItemID;  

                                     if ((this._ItemID != value))  

                                               if (this._Items.HasLoadedOrAssignedValue)  

                                               {  

                                                        throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();  

                                               }  

                                               this.OnItemIDChanging(value);  

                                               this._ItemID = value;  

                                               this.SendPropertyChanged("ItemID");  

                                               this.OnItemIDChanged();  

                   [Association(Name="FK_Accounts_Items", Storage="_Items", ThisKey="ItemID", OtherKey="ID", IsForeignKey=true)]  

                   public Items Items  

                                     return this._Items.Entity;  

                                     Items previousValue = this._Items.Entity;  

                                     if (((previousValue != value)   

                                                                 || (this._Items.HasLoadedOrAssignedValue == false)))  

                                               if ((previousValue != null))  

                                                        this._Items.Entity = null;  

                                                        previousValue.Accounts.Remove(this);  

                                               this._Items.Entity = value;  

                                               if ((value != null))  

                                                        value.Accounts.Add(this);  

                                                        this._ItemID = value.ID;  

                                               else 

                                                        this._ItemID = default(Nullable&lt;int&gt;);  

                                               this.SendPropertyChanged("Items");  

                   public event PropertyChangingEventHandler PropertyChanging;  

                   public event PropertyChangedEventHandler PropertyChanged;  

                   protected virtual void SendPropertyChanging()  

                            if ((this.PropertyChanging != null))  

                                     this.PropertyChanging(this, emptyChangingEventArgs);  

                   protected virtual void SendPropertyChanged(String propertyName)  

                            if ((this.PropertyChanged != null))  

                                     this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  

         [Table(Name="dbo.Items")]  

         public partial class Items : INotifyPropertyChanging, INotifyPropertyChanged  

                   private string _ItemName;  

                   private EntitySet&lt;Accounts&gt; _Accounts;  

    partial void OnItemNameChanging(string value);  

    partial void OnItemNameChanged();  

                   public Items()  

                            this._Accounts = new EntitySet&lt;Accounts&gt;(new Action&lt;Accounts&gt;(this.attach_Accounts), new Action&lt;Accounts&gt;(this.detach_Accounts));  

                   [Column(Storage="_ItemName", DbType="NVarChar(50)")]  

                   public string ItemName  

                                     return this._ItemName;  

                                     if ((this._ItemName != value))  

                                               this.OnItemNameChanging(value);  

                                               this._ItemName = value;  

                                               this.SendPropertyChanged("ItemName");  

                                               this.OnItemNameChanged();  

                   [Association(Name="FK_Accounts_Items", Storage="_Accounts", ThisKey="ID", OtherKey="ItemID", DeleteRule="NO ACTION")]  

                   public EntitySet&lt;Accounts&gt; Accounts  

                                     return this._Accounts;  

                                     this._Accounts.Assign(value);  

                   private void attach_Accounts(Accounts entity)  

                            this.SendPropertyChanging();  

                            entity.Items = this;  

                   }                   

                   private void detach_Accounts(Accounts entity)  

                            entity.Items = null;  

}  

#pragma warning restore 1591 

<b>3、 </b><b>把</b><b>SQL</b><b>实体代码添加到项目中</b>

A.        添加项目引用System.Data.Linq

B.        注释掉用System.Data.IDbConnection的构造函数,因为在WP中没有IDbConnection接口

C.        保持数据库实体对象中,表集合的命名是复数形式(注意是Account_db类中),即Accounts和Items

D.        实体类Table特性类的Name属性不要带dbo,如下:

[Table(Name="dbo.Accounts")]改成[Table(Name="Accounts")]

E.   实体类中的属性如果是string类型,最好用Column特性的DbType命名参数用NVarchar,如下:[Column(Storage="_ItemName", DbType="NVarChar(50)")]

<b>4、 </b><b>在</b><b>Windows Phone</b><b>下生成数据库</b>

可以在App类的Application_Launching事件方法中写入如下代码来创建WP中的数据库对象:

using (Test.Account_db db = new Account_db("Data Source='isostore:/test.sdf';Password=123"))  

            {                  

                if (db.DatabaseExists() == false)  

                {  

                    db.CreateDatabase();  

                }  

            } 

<b>5、 </b><b>操作数据</b>

操作数据的方法与 web和桌面开发是相同的,使用Linq To SQL方法即可。下面是Items实体对象的添加。

Account_db accountdb = new Account_db("Data Source='isostore:/test.sdf';Password='saiko2011'");  

            Items item = new Items();  

            item.ItemName = "收入";  

            accountdb.Items.InsertOnSubmit(item);  

            accountdb.SubmitChanges();  

            lb.ItemsSource = accountdb.Items; 

本文转自桂素伟51CTO博客,原文链接:http://blog.51cto.com/axzxs/762688 ,如需转载请自行联系原作者