WindowsPhone 中SQL CE数据库的使用

       WindowsPhone中有时候我们会一些数据的存储,这个时候我们有两种选择,一种是选择存在的独立存储文件中,一种是存储在数据库中。存储在独立存储文件中,这个相信很多用都会使用,这里不作为重点,本文主要讲一下在WindowsPhone中使用数据库SQL CE

下面开始一步一步的带领大家实现在WindowsPhone 中使用SQL CE数据库。(该示例引自WindowsPhone 7应用开发)

一、首先,我们需要创建一个EmployeeTable类,映射为数据库中的Employee

如下:

在创建之前需要添加引用:System.Data.Linq

同时引入命名空间:using System.Data.Linq.Mapping;

 [Table]//特性标识该类为映射为数库中的表

  //该类实现了INotifyPropertyChanged和INotifyPropertyChanging接口

    public class EmployeeTable:INotifyPropertyChanged,INotifyPropertyChanging

    {

        private int _employeeId;

        //将EmployeeID映射为表的主键,特性Column里的含义分别为:主键,自增,int型不为空,不为空等

        [Column(IsPrimaryKey = true, IsDbGenerated = true,DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]

        public int EmployeeID

        {

            get

            {

                return _employeeId;

            }

            set

            {

                if (_employeeId != value)

                {

                    NotifyPropertyChanging("EmployeeID");

                    _employeeId = value;

                    NotifyPropertyChanged("EmployeeID");

                }

            }

        }

        private string _employeeName;

        [Column]//EmployeeName属性为表中EmployeeName字段

        public string EmployeeName

        {

            get

            {

                return _employeeName;

            }

            set

            {

                if (_employeeName != value)

                {

                    NotifyPropertyChanging("EmployeeName");

                    _employeeName = value;

                    NotifyPropertyChanged("EmployeeName");

                }

            }

        }

        private string _employeeDesc;

        [Column]//将EmployeeDesc属性映射为表中EmployeeDesc字段

        public string EmployeeDesc

        {

            get

            {

                return _employeeDesc;

            }

            set

            {

                if (_employeeDesc != value)

                {

                    NotifyPropertyChanging("EmployeeDesc");

                    _employeeDesc = value;

                    NotifyPropertyChanged("EmployeeDesc");

                }

            }

        }

        //定义PropertyChanged事件用来通知页面,表字段数据发生了改变

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)

        {

            if (PropertyChanged != null)

            {

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }

        }

        //定义PropertyChanging事件通知数据上下文表的字段数据将要发生改变

        public event PropertyChangingEventHandler PropertyChanging;

        private void NotifyPropertyChanging(string propertyname)

        {

            if (PropertyChanging != null)

            {

                PropertyChanging(this, new PropertyChangingEventArgs(propertyname));

            }

        }

    }

通过以上的这些操作,我们已经基本上完成了Employee表的创建,映射为数据库中的EmployeeTable

二、下面我们来新建一个EmployeeDataContext.cs类文件,创建数据库的DataContent,该类继承自DataContent,在该类中定义连接字符串,如下:

首先需要引入命名空间:using system.data.Linq;

public class EmployeeDataContext:DataContext

    {

        //数据库连接字符串

        public static string DBConnectionString = "Data Source=isostore:/Employee.sdf";

        //传递数据库连接字符串到DataContext基类

        public EmployeeDataContext(string connectionString):base(connectionString)

        {

        }

        //定义员工信息表

        public Table<EmployeeTable> Employees;

    }

三、创建EmployeeCollection类,该类的主要作用为页面数据绑定的集合。如下:

    //绑定页面,进行显示用    

public class EmployeeCollection:INotifyPropertyChanged

{

    //用于通知属性的改变

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)

        {

            if (PropertyChanged != null)

            {

                PropertyChanged(this,new PropertyChangedEventArgs (propertyName));

            }

        }

        private ObservableCollection<EmployeeTable> _employeeTables;

//创建EmployeeTables属性用来绑定页面数据        

public ObservableCollection<EmployeeTable> EmployeeTables

        {

            get

            {

                return _employeeTables;

            }

            set

            {

                if (_employeeTables != value)

                {

                    _employeeTables = value;

                    NotifyPropertyChanged("EmployeeTables");

                }

            }

        }

    }

四、这样一个完整的数据库就创建完毕了,那么我们该如何使用呢?一般的情况下我们都是在程序启动的时候加载数据库,为此我们可以在App.xaml文件的Launching事件中做如下处理:

using (EmployeeDataContext db=new EmployeeDataContext(EmployeeDataContext.DBConnectionString))

           {

                if (db.DatabaseExists() == false)

                {

                    db.CreateDatabase();

                }

            }

五、下面做一个实例进行演示:

页面布局如下:

 

<phone:PhoneApplicationPage.Resources>

        <DataTemplate x:Key="listitem">

            <Grid HorizontalAlignment="Stretch" Width="440">

                <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="50"/>

                    <ColumnDefinition Width="*"/>

                    <ColumnDefinition Width="100"/>

                 </Grid.ColumnDefinitions>

                <TextBlock Text="{Binding EmployeeName}" FontSize="{StaticResource PhoneFontSizeLarge}" Grid.Column="1" 
VerticalAlignment="Center"/> <Button Grid.Column="2" Click="deleteButton_Click" x:Name="deleteButton" BorderThickness="0" Margin="0" Content="删除" ></Button> <Button Grid.Column="1" x:Name="editButton" Click="editButton_Click"BorderThickness="0" Margin="209,0,81,0" Content="编辑"
Grid.ColumnSpan="2"></Button> </Grid> </DataTemplate> </phone:PhoneApplicationPage.Resources> <!--LayoutRoot 是包含所有页面内容的根网格--> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel 包含应用程序的名称和页标题--> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="我的应用程序" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="EmployeeShow" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - 在此处放置其他内容--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock FontSize="24" Name="textBlock1" Text="员工名字: " Margin="12,22,330,544" /> <TextBlock FontSize="24" Margin="12,93,330,473" Name="textBlock2" Text="简介:" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="132,6,0,0" Name="txtname" Text="" VerticalAlignment="Top" Width="281" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="132,78,0,0" Name="txtdesc" Text="" VerticalAlignment="Top" Width="281" /> <Button Content="保存" Height="72" HorizontalAlignment="Left" Margin="243,150,0,0" Name="button2" VerticalAlignment="Top" Width="160" Click="button2_Click" /> <ListBox Height="293" HorizontalAlignment="Left" Margin="-12,228,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" ItemTemplate="{StaticResource listitem}" /> </Grid> </Grid> </phone:PhoneApplicationPage>

.cs页的处理代码如下:

public partial class EmployeeShow : PhoneApplicationPage

    {

        //创建DataContext用于操作独立的数据库

        private EmployeeDataContext employeeDB;

        private EmployeeCollection employeeCol = new EmployeeCollection();

      

  public EmployeeShow()

        {

            InitializeComponent();

    //创建EmployeeDataContext实例        

    employeeDB = new EmployeeDataContext(EmployeeDataContext.DBConnectionString);

            var employeeInDB = from EmployeeTable employee in employeeDB.Employees

                               select employee;

 //为页面创建数据绑定源            

employeeCol.EmployeeTables = new System.Collections.ObjectModel.ObservableCollection<EmployeeTable>(employeeInDB);

            listBox1.ItemsSource = employeeCol.EmployeeTables;

        }

        //删除信息        

private void deleteButton_Click(object sender, RoutedEventArgs e)

        {

            var button = sender as Button;

            if (button != null)

            {

                EmployeeTable edelete = button.DataContext as EmployeeTable;

                //

                employeeCol.EmployeeTables.Remove(edelete);

                employeeDB.Employees.DeleteOnSubmit(edelete);

                employeeDB.SubmitChanges();

            }

        }

     //保存信息        

private void button2_Click(object sender, RoutedEventArgs e)

        {

            if (txtname.Text != "" && txtdesc.Text != "")

            {

                //编辑状态

                if (State.Count > 0 && State["employee"] != null)

                {

                    EmployeeTable employee = (EmployeeTable)State["employee"];

                    employee.EmployeeName = txtname.Text;

                    employee.EmployeeDesc = txtdesc.Text;

                    employeeDB.SubmitChanges();

                    employeeCol.EmployeeTables.Add(employee);

                    State["employee"] = null;

                }

                Else//添加新的信息

                {

                    EmployeeTable newEmployee = new EmployeeTable

                    {

                        EmployeeName = txtname.Text,

                        EmployeeDesc = txtdesc.Text

                    };

                    employeeCol.EmployeeTables.Add(newEmployee);

                    employeeDB.Employees.InsertOnSubmit(newEmployee);

                    employeeDB.SubmitChanges();

                    txtname.Text = "";

                    txtdesc.Text = "";

                }

                listBox1.ItemsSource = employeeCol.EmployeeTables;

            }

            else

            {

                MessageBox.Show("姓名和简介不能为空!");

            }

        }

        //编辑信息     

   private void editButton_Click(object sender, RoutedEventArgs e)

        {

            var button = sender as Button;

            if (button != null)

            {

                EmployeeTable eedit = button.DataContext as EmployeeTable;

                txtname.Text = eedit.EmployeeName;

                txtdesc.Text = eedit.EmployeeDesc;

                State["employee"] = eedit;

                employeeCol.EmployeeTables.Remove(eedit);      

            }

        }

    }

效果如图:

WindowsPhone 中SQL CE数据库的使用

 

 

好了,到这里我们已经基本上实现了在WindowsPhone手机中使用SQLCE数据库了,希望可以对朋友们有所帮助。

你可能感兴趣的:(windows)