Язык программирования C#9 и платформа .NET5
Шрифт:
_schema = schema;
_tableName = tableName;
}
Далее реализуйте метод
GetSchemaTable
, который извлекает информацию SQL Server, касающуюся целевой таблицы:
public DataTable GetSchemaTable
{
using var schemaCommand =
new SqlCommand($"SELECT * FROM {_schema}.{_tableName}", _
connection);
using var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly);
return reader.GetSchemaTable;
}
Модифицируйте
SchemaTable
для создания словаря, который содержит поля целевой таблицы в порядке их следования внутри базы данных:
public MyDataReader(List<T> records, SqlConnection connection,
string schema, string tableName)
{
...
DataTable schemaTable = GetSchemaTable;
for (int x = 0; x<schemaTable?.Rows.Count;x++)
{
DataRow col = schemaTable.Rows[x];
var columnName = col.Field<string>("ColumnName");
_nameDictionary.Add(x,columnName);
}
}
Теперь показанные далее методы могут быть реализованы обобщенным образом, используя полученную посредством рефлексии информацию:
public int FieldCount => _propertyInfos.Length;
public object GetValue(int i)
=> _propertyInfos
.First(x=>x.Name.Equals(_nameDictionary[i],
StringComparison.OrdinalIgnoreCase))
.GetValue(Records[_currentIndex]);
Для справки ниже приведены остальные методы, которые должны присутствовать (но не реализованы):
public string GetName(int i) => throw new NotImplementedException;
public int GetOrdinal(string name) => throw new NotImplementedException;
public string GetDataTypeName(int i) => throw new NotImplementedException;
public Type GetFieldType(int i) => throw new NotImplementedException;
public int GetValues(object[] values) => throw new NotImplementedException;
public bool GetBoolean(int i) => throw new NotImplementedException;
public byte GetByte(int i) => throw new NotImplementedException;
public long GetBytes(int i, long fieldOffset, byte[] buffer,
int bufferoffset, int length)
=> throw new NotImplementedException;
public char GetChar(int i) => throw new NotImplementedException;
public long GetChars(int i, long fieldoffset, char[] buffer,
int bufferoffset, int length)
=> throw new NotImplementedException;
public Guid GetGuid(int i) => throw new NotImplementedException;
public short GetInt16(int i) => throw new NotImplementedException;
public int GetInt32(int i) => throw new NotImplementedException;
public long GetInt64(int i) => throw new NotImplementedException;
public float GetFloat(int i) => throw new NotImplementedException;
public double GetDouble(int i) => throw new NotImplementedException;
public string GetString(int i) => throw new NotImplementedException;
public decimal GetDecimal(int i) => throw new NotImplementedException;
public DateTime GetDateTime(int i) => throw new NotImplementedException;
public IDataReader GetData(int i) => throw new NotImplementedException;
public bool IsDBNull(int i) => throw new NotImplementedException;
object IDataRecord.this[int i] => throw new NotImplementedException;
object IDataRecord.this[string name] => throw new NotImplementedException;
public void Close => throw new NotImplementedException;
public DataTable GetSchemaTable => throw new NotImplementedException;
public bool NextResult => throw new NotImplementedException;
public int Depth { get; }
public bool IsClosed { get; }
public int RecordsAffected { get; }
Выполнение массового копирования
Добавьте в папку
BulkImport
новый файл открытого статического класса по имени ProcessBulkImport.cs
. Поместите в начало файла следующие операторы using
:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Data.SqlClient;
Добавьте код для поддержки открытия и закрытия подключений (похожий на код в классе
InventoryDal
):
private const string ConnectionString =
@"Data Source=.,5433;User Id=sa;Password=P@ssw0rd;Initial Catalog=AutoLot";
Поделиться с друзьями: