从单个 Entity Framework 行输出 class 的多个实例

Output multiple instances of class from single Entity Framework row

我们目前有以下代码:

return await Table.AsNoTracking().Select(d => new MyClass()
{
    Code = d.Code1,
    Name = d.Desc1,
    Type = "Test",
    Template = $"test-{item}"
}).Where(d =>
    !string.IsNullOrWhiteSpace(d.Code) &&
    !string.IsNullOrWhiteSpace(d.Name)
).Distinct().ToArrayAsync();

我们还有另一个执行此操作的查询:

return await Table.AsNoTracking().Select(d => new MyClass()
{
    Code = d.Code2,
    Name = d.Desc2,
    Type = "Test",
    Template = $"test-{item}"
}).Where(d =>
    !string.IsNullOrWhiteSpace(d.Code) &&
    !string.IsNullOrWhiteSpace(d.Name)
).Distinct().ToArrayAsync();

重要的是单个记录可以输出一个 class 的多个实例。 为了提高效率,最好将此作为单个查询执行并生成 class 的所有实例。

我试过类似下面的方法,但 Entity Framework 不知道如何转换它。有什么想法可以做吗?

return await Table.AsNoTracking().Select(d => new List<MyClass>()
{
    new MyClass()
    {
        Code = d.Code2,
        Name = d.Desc2,
        Type = "Test",
        Template = $"test-{item}"
    },
    new MyClass()
    {
        Code = d.Code1,
        Name = d.Desc1,
        Type = "test",
        Template = $"test-{item}"
    } 
}).SelectMany(d => d, (d, i) => i).Where(d =>
    !string.IsNullOrWhiteSpace(d.Code) &&
    !string.IsNullOrWhiteSpace(d.Name)
).Distinct().ToArrayAsync();

尝试使用Union,它应该甚至不需要调用Distict

var query1 = Table
    .Select(d => new MyClass()
    {
        Code = d.Code1,
        Name = d.Desc1,
        Type = "Test",
        Template = $"test-{item}"
    }).Where(d =>
        !string.IsNullOrWhiteSpace(d.Code) &&
        !string.IsNullOrWhiteSpace(d.Name)
    );

var query2 = Table
    .Select(d => new MyClass()
    {
        Code = d.Code2,
        Name = d.Desc2,
        Type = "Test",
        Template = $"test-{item}"
    }).Where(d =>
        !string.IsNullOrWhiteSpace(d.Code) &&
        !string.IsNullOrWhiteSpace(d.Name)
    );

var result = await query1.Union(query2)
    .ToArrayAsync();