我試圖使用System.Data
程序集(4.6.1)中的SqlBulkCopy
類使用代碼批量插入具有地理空間數據類型的表看起來大致是這樣(改編自https://github.com/MikaelEliasson/EntityFramework.Utilities):使用地理空間數據類型批量插入表時出現「指定類型未註冊」錯誤
public void InsertItems<T>(IEnumerable<T> items, string schema, string tableName, IList<ColumnMapping> properties, DbConnection storeConnection, int? batchSize)
{
using (var reader = new EFDataReader<T>(items, properties))
{
var con = (SqlConnection)storeConnection;
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (var copy = new SqlBulkCopy(con))
{
copy.BatchSize = batchSize ?? 15000; //default batch size
if (!string.IsNullOrWhiteSpace(schema))
{
copy.DestinationTableName = $"[{schema}].[{tableName}]";
}
else
{
copy.DestinationTableName = "[" + tableName + "]";
}
copy.NotifyAfter = 0;
foreach (var i in Enumerable.Range(0, reader.FieldCount))
{
copy.ColumnMappings.Add(i, properties[i].NameInDatabase);
}
copy.WriteToServer(reader); // <-- throws here
copy.Close();
}
}
}
直到我嘗試使用它與地理空間數據的表的偉大工程。當我這樣做時,我得到以下錯誤:
ERROR Swyfft.Console.TaskManager - Error running task SeedRating:
(InvalidOperationException) The given value of type DbGeography from the data source cannot be converted to type udt of the specified target column.;
(ArgumentException) Specified type is not registered on the target server.System.Data.Entity.Spatial.DbGeography, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.;
at Swyfft.Data.Utilities.SqlQueryProvider.InsertItems[T](IEnumerable`1 items, String schema, String tableName, IList`1 properties, DbConnection storeConnection, Nullable`1 batchSize) in C:\source\swyfft\swyf-website\Swyfft.Data.Utilities\SqlQueryProvider.cs:line 78
at Swyfft.Data.Utilities.EFBatchOperation`2.InsertAll[TEntity](IEnumerable`1 items, DbConnection connection, Nullable`1 batchSize) in C:\source\swyfft\swyf-website\Swyfft.Data.Utilities\EFBatchOperation.cs:line 138
at Swyfft.Data.Rating.RatingContext.BulkInsert[T](IEnumerable`1 entities, Nullable`1 batchSize) in C:\source\swyfft\swyf-website\Swyfft.Data.Rating\RatingContext.cs:line 69
at Swyfft.Seeding.CsvLoaders.CsvLoader.ProcessCsv[T](StreamReader streamReader, String fileName, ISwyfftContext ctx, Func`2 parserFunc) in C:\source\swyfft\swyf-website\Swyfft.Seeding\CsvLoaders\CsvLoader.cs:line 133
at Swyfft.Seeding.CsvLoaders.CsvLoader.InitializeCountyBlockQualities(String stateFilter) in C:\source\swyfft\swyf-website\Swyfft.Seeding\CsvLoaders\InitializeCountyBlockQualities.cs:line 35
我已經搜索了一下,沒有太大的效果。我追蹤了調用鏈,深入到SqlBulkCopy程序集的內部(謝謝,Resharper!),但是這個錯誤似乎隱藏得比我能挖掘的更深。我試過安裝(和加載)適當的SQL Server Types包(https://www.nuget.org/packages/Microsoft.SqlServer.Types/),但沒有骰子。
有什麼建議嗎?
是個壞主意。我解決了我自己的問題。 –