【问题标题】:How to use expressions to build a LINQ query dynamically when using an interface to get the column name?使用接口获取列名时如何使用表达式动态构建LINQ查询?
【发布时间】:2019-11-07 11:47:31
【问题描述】:

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

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

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 类型的键列表,该方法应该返回当前存在于数据库中的相关表。

查询如下所示:

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

BuildWhereExpression 中,我正在尝试创建一个适当的Expression&lt;Func&lt;TEntity, bool&gt;&gt;,在BuildSelectExpression 中,我正在尝试创建一个适当的Expression&lt;Func&lt;TEntity, TKey&gt;&gt;。但是,我正在努力创建 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"

但查询只返回一个包含“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 StackOverflow
{
    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 包:

  • Microsoft.EntityFrameworkCore,版本 3.0.0
  • Microsoft.EntityFrameworkCore.Sqlite,版本 3.0.0
  • Microsoft.Extensions.DependencyInjection,版本 3.0.0
  • Microsoft.Extensions.Logging.Console,版本 3.0.0

【问题讨论】:

  • 使用接口描述列名看起来不对,因为当时你需要属性名你没有实体实例。列名是静态(类型相关)信息,在 EF Core 中可以从模型元数据中获取 - 例如参见 stackoverflow.com/questions/55867725/…

标签: c# linq entity-framework-core linq-expressions


【解决方案1】:

在这种情况下,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);
}

【讨论】:

  • 我有点担心使用反射对性能的影响,尽管考虑到这不是在紧密循环中调用的,这可能不会成为问题。无论如何,谢谢,这让我朝着正确的方向前进。
  • 您可以随时缓存keyProperty 并执行一次。
【解决方案2】:

这是我最终为通用方法编写的代码:

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 为我指明了正确的方向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多