EF Core:从C#类创建SQL用户定义的类型

时间:2018-12-02 16:52:27

标签: c# sql-server entity-framework entity-framework-core

在我的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代码。

2 个答案:

答案 0 :(得分:2)

经过数小时的研究,我得出了大卫·布朗(David Browne)提出的相同结论,但无法完成。 但是,并不是所有的一切都丢失了,我设法扩展了默认的EF Core SQl Generator,使我能够使用相同的纯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的Configure服务(使用ASP.NET Core)中替换DbContextOptions中的服务:

services.AddDbContext<MyContext>(opt =>
    opt.UseSqlServer(_config.GetConnectionString("MyContextConnection"))
    .ReplaceService<IMigrationsSqlGenerator, CustomSqlServerMigrationsSqlGenerator>());

相关链接:

  1. https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/operations
  2. https://github.com/aspnet/EntityFrameworkCore/blob/release/2.1/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs

答案 1 :(得分:1)

我不知道会为实体生成用户定义表类型的任何东西。您已经必须使C#类与数据库表保持同步,因此您需要在此基础上附加表类型生成过程。

一种替代方法是使用JSON而不是TVP将数据传递到SQL Server。 EG:How to Write In Clause with EF FromSql?