我尝试使用SQL Server SMO类创建数据库,但创建db的行会抛出FailedOperationException。
内部异常(SmoException)有消息" PRIMARY文件组必须至少有一个文件。"。
但是我在代码中设置PRIMARY文件组(或者至少我认为我是)并且我将数据文件(.IsPrimaryFile = True)添加到组中。
我确定我遗漏了一些明显/简单的东西。
任何帮助将不胜感激: - )...
Imports Microsoft.SqlServer.Management.Smo
Dim serverName = "(local)"
Dim databaseName = "TestNew3"
Dim sourceSrv = New Server(serverName)
Dim db As Database
db = New Database(sourceSrv, databaseName)
db.AutoCreateStatisticsEnabled = True
db.AutoUpdateStatisticsEnabled = True
db.AutoUpdateStatisticsAsync = True
Dim fileGroup = New FileGroup(db, "PRIMARY")
fileGroup.IsDefault = True
db.FileGroups.Add(fileGroup)
Dim dataFile = New DataFile(
fileGroup,
databaseName,
String.Format(
"{0}\{1}.mdf",
sourceSrv.MasterDBPath,
databaseName))
dataFile.GrowthType = FileGrowthType.KB
dataFile.Growth = 10240
dataFile.IsPrimaryFile = True
Dim logFile = New LogFile(
db,
databaseName,
String.Format(
"{0}\{1}_log.ldf",
sourceSrv.MasterDBPath,
databaseName))
logFile.GrowthType = FileGrowthType.KB
logFile.Growth = 10240
db.LogFiles.Add(logFile)
db.Create() '<-- THROWS EXCEPTION ("The PRIMARY filegroup must have at least one file")
答案 0 :(得分:0)
看起来dataFile必须显式添加到fileGroup(即使它将fileGroup作为其构造函数的第一个参数传递,它也不会自行添加。)
dataFile.Growth = 10240
dataFile.IsPrimaryFile = True
fileGroup.Files.Add(dataFile)
原始代码中也存在一个小错误(.ldf名称不唯一,fileGroup.IsDefault设置为True导致错误)。
这是完整的工作代码:
Dim serverName = "(local)"
Dim databaseName = "TestNew5"
Dim sourceSrv = New Server(serverName)
Dim db As Database
db = New Database(sourceSrv, databaseName)
db.AutoCreateStatisticsEnabled = True
db.AutoUpdateStatisticsEnabled = True
db.AutoUpdateStatisticsAsync = True
Dim fileGroup = New FileGroup(db, "PRIMARY")
Dim dataFile = New DataFile(
fileGroup,
databaseName,
String.Format(
"{0}\{1}.mdf",
sourceSrv.MasterDBPath,
databaseName))
dataFile.GrowthType = FileGrowthType.KB
dataFile.Growth = 10240
dataFile.IsPrimaryFile = True
fileGroup.Files.Add(dataFile)
db.FileGroups.Add(fileGroup)
Dim logFile = New LogFile(
db,
databaseName + "_log",
String.Format(
"{0}\{1}_1.ldf",
sourceSrv.MasterDBPath,
databaseName))
logFile.GrowthType = FileGrowthType.KB
logFile.Growth = 10240
db.LogFiles.Add(logFile)
db.Create()