c# - 为枚举创建通用的 dbset 列表

标签 c# entity-framework-core

我正在编写一个简单的 .NET Core 库,以使用 EF Core 将数据从一个 SQL 数据库复制到另一个数据库。我没有为每个 DbSet 复制代码,而是试图找到一种方法来创建一个我可以枚举并创建一些逻辑的通用列表。

我已尝试创建一个元组来保存有关源表和目标表的信息,但无法定义通用 DbSet。

我还使用泛型创建了一个自定义类来设置 DbSet 类型,但由于每个类类型不同,无法将其添加到列表中。

示例方法:

public void Execute()
{
    var source = new SourceContext();
    var destination = new DestinationContext();

    Console.WriteLine("Processing table A");
    destination.RemoveRange(destination.TableA);
    destination.SaveChanges();

    destination.AddRange(source.TableA.AsNoTracking().ToList());
    destination.SaveChanges();
}

为了不复制其他表的代码,尝试使用元组,例如

var tables = new List<Tuple<string, DbSet<T>, DbSet<T>>>
{
    Tuple.Create("Table A", source.TableA, destination.TableA),
    Tuple.Create("Table B", source.TableB, destination.TableB)
}; 

问题在于使用通用 DbSet 定义元组,因为添加的每个项目都有不同的类型。

看着创建一个类来定义一个表,例如

internal class Table<TEntity> where TEntity : class
{
    internal string Name {get; set;}
    internal DbSet<TEntity> Source {get; set;}
    internal DbSet<TEntity> Destination {get; set;}

    internal Table(string name, DbSet<TEntity> source, DbSet<TEntity> destination)
    {
        Name = name;
        Source = source;
        Destination = destination;
    }
}

但是我该如何创建 List没有特定类型:

var tables = new List<T>
{
    new Table<TableA>("Table A", source.TableA, destination.TableA),
    new Table<TableB>("Table B", source.TableB, destination.TableB)
};

List需要用 <T> 类型实例化.

最佳答案

您通常这样做的方式是使用 List<Something>其中 Something是所有类型都支持的公共(public)基类或接口(interface)。目前,最接近的是 object ,但您可能能够向您的 Table<TEntity> 添加一些非通用 基类/接口(interface).但问题是:它有用吗?充其量你可以公开Name ;你不能有用地谈论DbSet<T>没有 <T> ,除了可能作为非通用 IEnumerable/IQueryable ;所以:

internal interface ITable
{
    string Name {get;}
    IQueryable Source {get;}
    IQueryable Destination {get;}
    Type Type {get;}
}

并使用List<ITable>

在哪里Table<T>变成:

internal class Table<TEntity> : ITable where TEntity : class
{
    internal string Name {get; set;}
    internal DbSet<TEntity> Source {get; set;}
    internal DbSet<TEntity> Destination {get; set;}

    string ITable.Name => Name;
    IQueryable ITable.Source => Source;
    IQueryable ITable.Destination => Destination;
    Type ITable.Type => typeof(T);

    internal Table(string name, DbSet<TEntity> source, DbSet<TEntity> destination)
    {
        Name = name;
        Source = source;
        Destination = destination;
    }
}

关于c# - 为枚举创建通用的 dbset 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56775825/

相关文章:

c# - 在 MVC 中从 javascript 调用方法

c# - Blob 代码下载速度比 MS Azure Storage Explorer 慢得多

c# - "Sequence contains more than one element"将数据库数据转换为列表时

mysql - 在 EntityFrameworkCore 中加载相关数据时出错

c# - Entity Framework Core 两个外键 - 同一张表

c# - visual studio c# DataGridView 在排序后保持背景颜色

c# - 为什么在面向 .netstandard 1.3 时不能使用嵌入式资源 (resx)?

c# - 针对 C++ 和 C# 的代码生成工具

performance - Entity Framework Core 插入多个实体类似于 SQL 单个插入语句

c# - 无法通过 EF Core 找到 Oracle 表