Windows Phone 7.1 支持 SQL Server CE 和 LINQ to SQL,以及通过 DatabaseSchemaUpdater 升级数据库。
在其他平台上,我会阅读数据库模式表(例如sys.objects
)以查看当前模式并确定需要升级哪些表/列。
鉴于在 Windows Phone 上不允许直接 SQL 访问,如何检索当前的数据库架构?
Windows Phone 7.1 支持 SQL Server CE 和 LINQ to SQL,以及通过 DatabaseSchemaUpdater 升级数据库。
在其他平台上,我会阅读数据库模式表(例如sys.objects
)以查看当前模式并确定需要升级哪些表/列。
鉴于在 Windows Phone 上不允许直接 SQL 访问,如何检索当前的数据库架构?
SQL Server CE 仍然包括INFORMATION_SCHEMA.TABLES
andINFORMATION_SCHEMA.COLUMNS
表,但访问它们有点棘手,因为不允许直接 SQL 访问。
但是,您可以创建DataContext
映射到这些表的映射:
public class SchemaContext : DataContext
{
public SchemaContext()
: base("Data Source=isostore:/Database.sdf")
{
if (!this.DatabaseExists())
{
throw new InvalidOperationException("Cannot use the SchemaContext on a database which doesn't exist");
}
}
public Table<Table> Tables;
public Table<Column> Columns;
[Table(Name = "INFORMATION_SCHEMA.Columns")]
public class Column
{
[Column(Name = "TABLE_NAME")]
public string TableName { get; set; }
[Column(Name = "COLUMN_NAME")]
public string Name { get; set; }
[Column(Name = "DATA_TYPE")]
public string DataType { get; set; }
[Column(Name = "ORDINAL_POSITION")]
public int OrdinalPosition { get; set; }
[Column(Name = "IS_NULLABLE")]
public string IsNullableString { get; set; }
public bool IsNullable
{
get { return this.IsNullableString == "YES"; }
set { this.IsNullableString = value ? "YES" : "NO"; }
}
}
[Table(Name = "INFORMATION_SCHEMA.Tables")]
public class Table
{
[Column(Name = "TABLE_NAME")]
public string Name { get; set; }
[Column(Name = "TABLE_TYPE")]
public string Type { get; set; }
}
}
然后,您可以使用以下代码读取架构:
using (var schemaContext = new SchemaContext())
{
foreach (var table in schemaContext.Tables)
{
}
}
为这些表创建单独的上下文很重要,否则DataContext.CreateDatabase
调用将尝试创建这些模式表,这将失败。
MSDN 上有一个为 Windows Phone 更新本地数据库应用程序的演练,它提倡使用DatabaseSchemaVersion
on the DatabaseSchemaUpdater
- 即:
// Set the new database version.
DatabaseSchemaUpdater dbUpdater = db.CreateDatabaseSchemaUpdater();
dbUpdater.DatabaseSchemaVersion = APP_VERSION;
dbUpdater.Execute();
您可以查询版本并添加您在每个版本中添加的位,而不必担心当前架构(毕竟,只要您记得保持版本号正确更新,它就会是一个已知配置。)