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

问题描述 投票:2回答:1

我正在使用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

基本上,给定一个DbSet包含类型为[[TEntity的实体和类型为TKey的键的列表,该方法应返回数据库中相关表中当前存在的键的列表。] >查询看起来像这样:

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"

但是查询仅返回包含“ 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
  • 我正在使用Entity Framework Core来存储和检索一些数据。我正在尝试编写一种通用方法,该方法适用于任何DbSet

    ,以避免代码重复。此方法运行...

  • c# linq entity-framework-core linq-expressions
    1个回答
    0
    投票
    在这种情况下,IEntityWithKey接口是冗余的。要从KeyPropertyName方法访问BuildSelectExpression值,您需要具有实体实例,但只有Type对象。
    © www.soinside.com 2019 - 2024. All rights reserved.