在我的 SQL 数据库中,我存储了采用表值参数的过程和函数。我可以创建表值参数并使用纯 C# 从类型 T 的任何实体列表中填充它,如下所示:
DataTable table = new DataTable();
var props = typeof(T).GetProperties();
var columns = props.Select(p => new DataColumn(p.Name, p.PropertyType));
table.Columns.AddRange(columns.ToArray());
List<T> entities = GetEntities();
foreach (var entity in entities)
{
DataRow row = table.NewRow();
foreach (var prop in props)
{
row[prop.Name] = prop.GetValue(entity);
}
table.Rows.Add(row);
}
var tvp = new SqlParameter("@Entities", table) { TypeName = "dbo.T", SqlDbType = SqlDbType.Structured };
但是为了将上面的TVP传递给存储过程,必须先在sql server中创建一个相应的用户自定义类型T。到目前为止,如果不使用原始 SQL,我无法找到一种方法来执行此操作。像这样:
-- I want to avoid this
CREATE TYPE [dbo].[T] AS TABLE(
[Id] [INT] NOT NULL,
[Name] [varchar](255) NULL,
)
有没有办法不用写SQL就可以从C#类型T定义SQL用户自定义列表?某处已经有将 C# 映射到 SQL 类型的库,我不想重新发明轮子并编写难以维护并且很容易与 C# 类不同步的 SQL 代码。
最佳答案
经过几个小时的研究,我得出了 David Browne 所建议的相同结论,它不能在本地完成。 然而,并非一切都丢失了,我设法扩展了默认的 EF Core SQl 生成器,以允许我在迁移中使用相同的纯 C# 语法创建和删除表来手动创建和删除用户定义的表类型,而没有提及 SQL 数据类型(例如 nvarchar) .例如在迁移文件中:
migrationBuilder.CreateUserDefinedTableType(
name: "T",
schema: "dto",
columns: udt => new
{
// Example columns
Id = udt.Column<int>(nullable: false),
Date = udt.Column<DateTime>(nullable: false),
Memo = udt.Column<string>(maxLength: 256, nullable: true)
}
);
我正在分享下面的代码:
/// <summary>
/// A <see cref="MigrationOperation"/> for creating a new user-defined table type
/// </summary>
public class CreateUserDefinedTableTypeOperation : MigrationOperation
{
/// <summary>
/// The name of the user defined table type.
/// </summary>
public virtual string Name { get; set; }
/// <summary>
/// The schema that contains the user defined table type, or <c>null</c> if the default schema should be used.
/// </summary>
public virtual string Schema { get; set; }
/// <summary>
/// An ordered list of <see cref="AddColumnOperation" /> for adding columns to the user defined list.
/// </summary>
public virtual List<AddColumnOperation> Columns { get; } = new List<AddColumnOperation>();
}
/// <summary>
/// A <see cref="MigrationOperation"/> for dropping an existing user-defined table type
/// </summary>
public class DropUserDefinedTableTypeOperation : MigrationOperation
{
/// <summary>
/// The name of the user defined table type.
/// </summary>
public virtual string Name { get; set; }
/// <summary>
/// The schema that contains the user defined table type, or <c>null</c> if the default schema should be used.
/// </summary>
public virtual string Schema { get; set; }
}
/// <summary>
/// A builder for <see cref="CreateUserDefinedTableTypeOperation" /> operations.
/// </summary>
/// <typeparam name="TColumns"> Type of a typically anonymous type for building columns. </typeparam>
public class UserDefinedTableTypeColumnsBuilder
{
private readonly CreateUserDefinedTableTypeOperation _createTableOperation;
/// <summary>
/// Constructs a builder for the given <see cref="CreateUserDefinedTableTypeOperation" />.
/// </summary>
/// <param name="createUserDefinedTableTypeOperation"> The operation. </param>
public UserDefinedTableTypeColumnsBuilder(CreateUserDefinedTableTypeOperation createUserDefinedTableTypeOperation)
{
_createTableOperation = createUserDefinedTableTypeOperation ??
throw new ArgumentNullException(nameof(createUserDefinedTableTypeOperation));
}
public virtual OperationBuilder<AddColumnOperation> Column<T>(
string type = null,
bool? unicode = null,
int? maxLength = null,
bool rowVersion = false,
string name = null,
bool nullable = false,
object defaultValue = null,
string defaultValueSql = null,
string computedColumnSql = null,
bool? fixedLength = null)
{
var operation = new AddColumnOperation
{
Schema = _createTableOperation.Schema,
Table = _createTableOperation.Name,
Name = name,
ClrType = typeof(T),
ColumnType = type,
IsUnicode = unicode,
MaxLength = maxLength,
IsRowVersion = rowVersion,
IsNullable = nullable,
DefaultValue = defaultValue,
DefaultValueSql = defaultValueSql,
ComputedColumnSql = computedColumnSql,
IsFixedLength = fixedLength
};
_createTableOperation.Columns.Add(operation);
return new OperationBuilder<AddColumnOperation>(operation);
}
}
/// <summary>
/// An extended version of the default <see cref="SqlServerMigrationsSqlGenerator"/>
/// which adds functionality for creating and dropping User-Defined Table Types of SQL
/// server inside migration files using the same syntax as creating and dropping tables,
/// to use this generator, register it using <see cref="DbContextOptionsBuilder.ReplaceService{ISqlMigr, TImplementation}"/>
/// in order to replace the default implementation of <see cref="IMigrationsSqlGenerator"/>
/// </summary>
public class CustomSqlServerMigrationsSqlGenerator : SqlServerMigrationsSqlGenerator
{
public CustomSqlServerMigrationsSqlGenerator(
MigrationsSqlGeneratorDependencies dependencies,
IMigrationsAnnotationProvider migrationsAnnotations) : base(dependencies, migrationsAnnotations)
{
}
protected override void Generate(
MigrationOperation operation,
IModel model,
MigrationCommandListBuilder builder)
{
if (operation is CreateUserDefinedTableTypeOperation createUdtOperation)
{
GenerateCreateUdt(createUdtOperation, model, builder);
}
else if(operation is DropUserDefinedTableTypeOperation dropUdtOperation)
{
GenerateDropUdt(dropUdtOperation, builder);
}
else
{
base.Generate(operation, model, builder);
}
}
private void GenerateCreateUdt(
CreateUserDefinedTableTypeOperation operation,
IModel model,
MigrationCommandListBuilder builder)
{
builder
.Append("CREATE TYPE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema))
.AppendLine(" AS TABLE (");
using (builder.Indent())
{
for (var i = 0; i < operation.Columns.Count; i++)
{
var column = operation.Columns[i];
ColumnDefinition(column, model, builder);
if (i != operation.Columns.Count - 1)
{
builder.AppendLine(",");
}
}
builder.AppendLine();
}
builder.Append(")");
builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator).EndCommand();
}
private void GenerateDropUdt(
DropUserDefinedTableTypeOperation operation,
MigrationCommandListBuilder builder)
{
builder
.Append("DROP TYPE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema))
.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator)
.EndCommand();
}
}
public static class MigrationBuilderExtensions
{
/// <summary>
/// Builds an <see cref="CreateUserDefinedTableTypeOperation" /> to create a new user-defined table type.
/// </summary>
/// <typeparam name="TColumns"> Type of a typically anonymous type for building columns. </typeparam>
/// <param name="name"> The name of the user-defined table type. </param>
/// <param name="columns">
/// A delegate using a <see cref="ColumnsBuilder" /> to create an anonymous type configuring the columns of the user-defined table type.
/// </param>
/// <param name="schema"> The schema that contains the user-defined table type, or <c>null</c> to use the default schema. </param>
/// <returns> A builder to allow annotations to be added to the operation. </returns>
public static MigrationBuilder CreateUserDefinedTableType<TColumns>(
this MigrationBuilder builder,
string name,
Func<UserDefinedTableTypeColumnsBuilder, TColumns> columns,
string schema = null)
{
var createUdtOperation = new CreateUserDefinedTableTypeOperation
{
Name = name,
Schema = schema
};
var columnBuilder = new UserDefinedTableTypeColumnsBuilder(createUdtOperation);
var columnsObject = columns(columnBuilder);
var columnMap = new Dictionary<PropertyInfo, AddColumnOperation>();
foreach (var property in typeof(TColumns).GetTypeInfo().DeclaredProperties)
{
var addColumnOperation = ((IInfrastructure<AddColumnOperation>)property.GetMethod.Invoke(columnsObject, null)).Instance;
if (addColumnOperation.Name == null)
{
addColumnOperation.Name = property.Name;
}
columnMap.Add(property, addColumnOperation);
}
builder.Operations.Add(createUdtOperation);
return builder;
}
/// <summary>
/// Builds an <see cref="DropUserDefinedTableTypeOperation" /> to drop an existing user-defined table type.
/// </summary>
/// <param name="name"> The name of the user-defined table type to drop. </param>
/// <param name="schema"> The schema that contains the user-defined table type, or <c>null</c> to use the default schema. </param>
/// <returns> A builder to allow annotations to be added to the operation. </returns>
public static MigrationBuilder DropUserDefinedTableType(
this MigrationBuilder builder,
string name,
string schema = null)
{
builder.Operations.Add(new DropUserDefinedTableTypeOperation
{
Name = name,
Schema = schema
});
return builder;
}
}
在迁移可以使用上述代码之前,您需要在 Startup 的配置服务(使用 ASP.NET Core)中替换 DbContextOptions 中的服务,如下所示:
services.AddDbContext<MyContext>(opt =>
opt.UseSqlServer(_config.GetConnectionString("MyContextConnection"))
.ReplaceService<IMigrationsSqlGenerator, CustomSqlServerMigrationsSqlGenerator>());
相关链接:
关于c# - EF 核心 : Create a SQL user-defined type from a C# class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53582485/