我们正在尝试访问Microsoft.SqlServer.Management.Smo.Server
对象的DefaultFile
成员。经过大量调试后,结果第一次访问成员崩溃,但可以很好地访问。在调试窗口中查看变量是第一次返回一个异常,第二次和以后的所有时间都返回正确的值。访问Microsoft.SqlServer.Management.Smo.Server对象的成员恰好崩溃一次
任server.DefaultFile
或server.DefaultLog
第一接入抛出这样一个异常:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Microsoft.SqlServer.Management.Smo.BitStorage.SetBit(Int32 itemIndex, BitIndex bitIndex, Boolean value)
at Microsoft.SqlServer.Management.Smo.PropertyCollection.SetRetrieved(Int32 index, Boolean val)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.AddObjectPropsFromDataReader(IDataReader reader, Boolean skipIfDirty, Int32 startColIdx, Int32 endColIdx)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.ImplInitialize(String[] fields, OrderBy[] orderby)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.Initialize(Boolean allProperties)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.OnPropertyMissing(String propname, Boolean useDefaultValue)
at Microsoft.SqlServer.Management.Smo.PropertyCollection.GetValueWithNullReplacement(String propertyName, Boolean throwOnNullValue, Boolean useDefaultOnMissingValue)
at Microsoft.SqlServer.Management.Smo.Server.get_DefaultFile()
at my function... etc etc
的第一次访问碰撞非常concistent,所以做什么可怕的事情像下面周围完全问题得到:
using (var sqlConnection = new SqlConnection(sourceDatabaseConnectionString.ConnectionString))
{
var svrConnection = new ServerConnection(sqlConnection);
var server = new Server(svrConnection);
// begin mega hack
try
{
// crashes on first access
var dummy = server.DefaultFile;
}
catch
{
// do absolutely nothing
}
// end mega hack
// business as usual...
var defaultFile = server.DefaultFile;
}
当然,我们不喜欢这样的代码(即使它只存在于我们的内部工具中),所以我们欢迎任何有关这种情况的原因。我们唯一的线索是我们最近将SQL Server 2012的一些实例升级到了SQL Server 2014.在安装了SQL Server 2014的计算机上本地运行代码时,我们有时可以解决这个问题。运行此代码的生产计算机根本没有安装,但引用了DLL。但是,在运行代码时调试打印程序集版本时,我们找不到使用版本的任何差异。
首先,SMO在日期结束时点击数据库,您是否有权查看“VIEW SERVER STATE/DEFINITION”? – lad2025
第二:用户数据库文件的默认位置是否与系统数据库文件相同?如果是这样的话,DefaultFile和DefaultLog属性永远不会被初始化。参见[这里](http://sqlblog.com/blogs/allen_white/archive/2009/02/19/finding-your-default-file-locations-in-smo.aspx),PowerShell等价物('if($ server .DefaultFile){$ server.DefaultFile} else {$ server.InstallDataDirectory +'\'+'Data'}') – lad2025