How to create a SQL Server CE 3.5 database utilisting a .NET CF 3.5 extension method:
1. Add a semi colon delimited resource file to your .NET CF mobile project.
1. Add a semi colon delimited resource file to your .NET CF mobile project.
- CREATE TABLE OrderHeader(
- [ID] uniqueidentifier not null,
- [CustomerID] uniqueidentifier not null,
- [ReqestedDlvryDate] datetime not null,
- [Comments] nvarchar(1000),
- [CreateDate] datetime not null,
- [CreatedByID] uniqueidentifier not null,
- [LastEditDate] datetime null,
- [LastEditBy] uniqueidentifier not null,
- CONSTRAINT [PK_OrderHeader] PRIMARY KEY ( [ID] )
- );
- CREATE TABLE OrderDetail(
- [ID] uniqueidentifier not null,
- [OrderID] uniqueidentifier not null,
- [ProductID] uniqueidentifier not null,
- [Qty] int not null,
- CONSTRAINT [PK_OrderDetail] PRIMARY KEY ( [ID] ),
- CONSTRAINT [FK_OrderHeader] FOREIGN KEY([OrderID]) REFERENCES [OrderHeader]([ID])
- );
2. Add an extension method on System.Data.SqlServerCE.SqlCeEngine to create the
database based on the semi colon delimited string passed in from the resorce file:
database based on the semi colon delimited string passed in from the resorce file:
- using System;
- using System.Data;
- using System.Data.Common;
- using System.Data.SqlServerCe;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- namespace SQLCEDatabaseDemo.ExtensionMethods
- {
- public static class Extensions
- {
- public static bool CreateDatabase(this SqlCeEngine sqlceDB, string commands)
- {
- bool success = false;
- SqlCeConnection sqlCon = null;
- try
- {
- sqlCon = new SqlCeConnection(sqlceDB.LocalConnectionString);
- if (!System.IO.File.Exists(sqlCon.DataSource))
- {
- sqlceDB.CreateDatabase();
- sqlCon.Open();
- string[] sqlStatements = commands.Split(';');
- SqlCeCommand cmd = sqlCon.CreateCommand();
- foreach (string cmdText in sqlStatements)
- {
- if (!String.IsNullOrEmpty(cmdText.Trim()))
- {
- cmd.CommandText = cmdText; cmd.ExecuteNonQuery();
- }
- } success = true;
- }
- }
- finally
- {
- if (sqlCon != null)
- {
- sqlCon.Close(); sqlCon.Dispose();
- }
- } return success;
- }
- public static void DeleteDatabase(this SqlCeEngine sqlceDB, string path)
- {
- System.IO.File.Delete(path);
- }
- }
- }
3. Execute using the following code
- string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
- string con = String.Format("data source='{0}\\testdb.sdf'; mode=Exclusive;", path);
- using(System.Data.SqlServerCe.SqlCeEngine eng = new System.Data.SqlServerCe.SqlCeEngine(con))
- {
- if (eng.CreateDatabase(Properties.Resources.CreateSchema))
- {
- MessageBox.Show("DB created successfully");
- }
- }
댓글 없음:
댓글 쓰기