使用接口获取列名时如何使用表达式动态构建LINQ查询?

How to use expressions to build a LINQ query dynamically when using an interface to get the column name?

我正在使用 Entity Framework Core 来存储和检索一些数据。我正在尝试编写一个适用于任何 DbSet<T> 的通用方法,以避免代码重复。此方法针对集合运行 LINQ 查询,为此它需要知道 "key" 列(即 table 的主键)。

为了帮助解决这个问题,我定义了一个接口,return 是代表键列的 属性 的名称。然后实体实现这个接口。因此我有这样的东西:

interface IEntityWithKey
{
    string KeyPropertyName { get; }
}

class FooEntity : IEntityWithKey
{
    [Key] public string FooId { get; set; }
    [NotMapped] public string KeyPropertyName => nameof(FooId);
}

class BarEntity : IEntityWithKey
{
    [Key] public string BarId { get; set; }
    [NotMapped] public string KeyPropertyName => nameof(BarId);
}

我尝试编写的方法具有此签名:

static List<TKey> GetMatchingKeys<TEntity, TKey>(DbSet<TEntity> dbSet, List<TKey> keysToFind)
    where TEntity : class, IEntityWithKey

基本上,给定包含 TEntity 类型的实体的 DbSet 和 TKey 类型的键列表,该方法应该 return 数据库中相关 table 当前存在的键列表。

查询如下所示:

dbSet.Where(BuildWhereExpression()).Select(BuildSelectExpression()).ToList()

BuildWhereExpression 中,我试图创建一个合适的 Expression<Func<TEntity, bool>>,在 BuildSelectExpression 中,我试图创建一个合适的 Expression<Func<TEntity, TKey>>。但是,我正在为创建 Select() 表达式而苦苦挣扎,这是两者中比较容易的。这是我目前所拥有的:

Expression<Func<TEntity, TKey>> BuildSelectExpression()
{
    // for a FooEntity, would be:  x => x.FooId
    // for a BarEntity, would be:  x => x.BarId

    ParameterExpression parameter = Expression.Parameter(typeof(TEntity));
    MemberExpression property1 = Expression.Property(parameter, nameof(IEntityWithKey.KeyPropertyName));
    MemberExpression property2 = Expression.Property(parameter, property1.Member as PropertyInfo);
    UnaryExpression result = Expression.Convert(property2, typeof(TKey));
    return Expression.Lambda<Func<TEntity, TKey>>(result, parameter);
}

这会运行,传递给数据库的查询看起来是正确的,但我得到的只是键 属性 名称的列表。例如,这样调用:

List<string> keys = GetMatchingKeys(context.Foos, new List<string> { "foo3", "foo2" });

它生成这个查询,看起来不错(注意:还没有 Where() 实现):

SELECT "f"."FooId"
FROM "Foos" AS "f"

但查询只是 return 一个包含 "FooId" 的列表,而不是存储在数据库中的实际 ID。

我觉得我已经接近解决方案了,但我只是在绕圈子表达一些东西,之前没有做过太多。如果有人可以帮助 Select() 表达式,那将是一个开始。

完整代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Whosebug
{
    interface IEntityWithKey
    {
        string KeyPropertyName { get; }
    }

    class FooEntity : IEntityWithKey
    {
        [Key] public string FooId { get; set; }
        [NotMapped] public string KeyPropertyName => nameof(FooId);
    }

    class BarEntity : IEntityWithKey
    {
        [Key] public string BarId { get; set; }
        [NotMapped] public string KeyPropertyName => nameof(BarId);
    }

    class TestContext : DbContext
    {
        public TestContext(DbContextOptions options) : base(options) { }
        public DbSet<FooEntity> Foos { get; set; }
        public DbSet<BarEntity> Bars { get; set; }
    }

    class Program
    {
        static async Task Main()
        {
            IServiceCollection services = new ServiceCollection();
            services.AddDbContext<TestContext>(
            options => options.UseSqlite("Data Source=./test.db"),
                contextLifetime: ServiceLifetime.Scoped,
                optionsLifetime: ServiceLifetime.Singleton);
            services.AddLogging(
                builder =>
                {
                    builder.AddConsole(c => c.IncludeScopes = true);
                    builder.AddFilter(DbLoggerCategory.Infrastructure.Name, LogLevel.Error);
                });
            IServiceProvider serviceProvider = services.BuildServiceProvider();

            var context = serviceProvider.GetService<TestContext>();
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.Foos.AddRange(new FooEntity { FooId = "foo1" }, new FooEntity { FooId = "foo2" });
            context.Bars.Add(new BarEntity { BarId = "bar1" });
            await context.SaveChangesAsync();

            List<string> keys = GetMatchingKeys(context.Foos, new List<string> { "foo3", "foo2" });
            Console.WriteLine(string.Join(", ", keys));

            Console.WriteLine("DONE");
            Console.ReadKey(intercept: true);
        }

        static List<TKey> GetMatchingKeys<TEntity, TKey>(DbSet<TEntity> dbSet, List<TKey> keysToFind)
            where TEntity : class, IEntityWithKey
        {
            return dbSet
                //.Where(BuildWhereExpression())   // commented out because not working yet
                .Select(BuildSelectExpression()).ToList();

            Expression<Func<TEntity, bool>> BuildWhereExpression()
            {
                // for a FooEntity, would be:  x => keysToFind.Contains(x.FooId)
                // for a BarEntity, would be:  x => keysToFind.Contains(x.BarId)

                throw new NotImplementedException();
            }

            Expression<Func<TEntity, TKey>> BuildSelectExpression()
            {
                // for a FooEntity, would be:  x => x.FooId
                // for a BarEntity, would be:  x => x.BarId

                ParameterExpression parameter = Expression.Parameter(typeof(TEntity));
                MemberExpression property1 = Expression.Property(parameter, nameof(IEntityWithKey.KeyPropertyName));
                MemberExpression property2 = Expression.Property(parameter, property1.Member as PropertyInfo);
                UnaryExpression result = Expression.Convert(property2, typeof(TKey));
                return Expression.Lambda<Func<TEntity, TKey>>(result, parameter);
            }
        }
    }
}

这使用以下 NuGet 包:

在这种情况下IEntityWithKey接口是多余的。 要从 BuildSelectExpression 方法访问 KeyPropertyName 值,您需要有实体实例,但您只有 Type 对象。

您可以使用反射来查找键 属性 名称:

Expression<Func<TEntity, TKey>> BuildSelectExpression()
{
    // Find key property
    PropertyInfo keyProperty = typeof(TEntity).GetProperties()
        .Where(p => p.GetCustomAttribute<KeyAttribute>() != null)
        .Single();

    ParameterExpression parameter = Expression.Parameter(typeof(TEntity));
    MemberExpression result = Expression.Property(parameter, keyProperty);
    // UnaryExpression result = Expression.Convert(property1, typeof(TKey)); this is also redundant
    return Expression.Lambda<Func<TEntity, TKey>>(result, parameter);
}

这是我为通用方法最终得到的代码:

static List<TKey> GetMatchingKeys<TEntity, TKey>(DbSet<TEntity> dbSet, List<TKey> keysToFind)
    where TEntity : class, IEntityWithKey
{
    PropertyInfo keyProperty = typeof(TEntity).GetProperties().Single(x => x.GetCustomAttribute<KeyAttribute>() != null);
    return dbSet.Where(BuildWhereExpression()).Select(BuildSelectExpression()).ToList();

    Expression<Func<TEntity, bool>> BuildWhereExpression()
    {
        ParameterExpression entity = Expression.Parameter(typeof(TEntity));
        MethodInfo containsMethod = typeof(List<TKey>).GetMethod("Contains");
        ConstantExpression keys = Expression.Constant(keysToFind);
        MemberExpression property = Expression.Property(entity, keyProperty);
        MethodCallExpression body = Expression.Call(keys, containsMethod, property);
        return Expression.Lambda<Func<TEntity, bool>>(body, entity);
    }

    Expression<Func<TEntity, TKey>> BuildSelectExpression()
    {
        ParameterExpression entity = Expression.Parameter(typeof(TEntity));
        MemberExpression body = Expression.Property(entity, keyProperty);
        return Expression.Lambda<Func<TEntity, TKey>>(body, entity);
    }
}

最终不需要接口,因为代码可以利用 EF Core 对 [Key] 属性的使用。

感谢@Krzysztof 为我指明了正确的方向。