【发布时间】: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<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
【问题讨论】:
-
使用接口描述列名看起来不对,因为当时你需要属性名你没有实体实例。列名是静态(类型相关)信息,在 EF Core 中可以从模型元数据中获取 - 例如参见 stackoverflow.com/questions/55867725/…
标签: c# linq entity-framework-core linq-expressions