EF Core 元数据服务可用于获取有关实体主键的信息,例如
var entityType = context.Model.FindEntityType(typeof(T));
var primaryKey = entityType.FindPrimaryKey();
然后可以使用此信息来构建动态相等比较器:
public static Expression<Func<T, T, bool>> GetPrimaryKeyCompareExpression<T>(this DbContext context)
{
var entityType = context.Model.FindEntityType(typeof(T));
var primaryKey = entityType.FindPrimaryKey();
var first = Expression.Parameter(typeof(T), "first");
var second = Expression.Parameter(typeof(T), "second");
var body = primaryKey.Properties
.Select(p => Expression.Equal(
Expression.Property(first, p.PropertyInfo),
Expression.Property(second, p.PropertyInfo)))
.Aggregate(Expression.AndAlso); // handles composite PKs
return Expression.Lambda<Func<T, T, bool>>(body, first, second);
}
反过来,它可以被编译以委托并在 LINQ to Objects 中使用(因为您使用的是IEnumerable
s)查询,例如
var setA = context.Set<T>().AsEnumerable();
var setB = context2.Set<T>().AsEnumerable();
var comparePKs = context.GetPrimaryKeyCompareExpression<T>().Compile();
var notExistsOnA = setB
.Where(b => !setA.Any(a => comparePKs(a, b)))
.ToList();
但请注意,在 LINQ to Objects 中,!Any(...)
内部查询条件效率低下,因为它是线性搜索操作,因此产生的时间复杂度是二次的 ( O(Na * Nb
),因此您将遇到更大数据集的性能问题。
所以一般来说使用连接运算符会更好。但不是比较,它需要键选择器,它也可以类似于上面的构建,但是这次发出Tuple
实例(为了处理复合 PK),例如
public static Expression<Func<T, object>> GetPrimaryKeySelector<T>(this DbContext context)
{
var entityType = context.Model.FindEntityType(typeof(T));
var primaryKey = entityType.FindPrimaryKey();
var item = Expression.Parameter(typeof(T), "item");
var body = Expression.Call(
typeof(Tuple), nameof(Tuple.Create),
primaryKey.Properties.Select(p => p.ClrType).ToArray(),
primaryKey.Properties.Select(p => Expression.Property(item, p.PropertyInfo)).ToArray()
);
return Expression.Lambda<Func<T, object>>(body, item);
}
并且可以如下使用
var selectPK = context.GetPrimaryKeySelector<T>().Compile();
var notExistsOnA = setB
.GroupJoin(setA, selectPK, selectPK, (b, As) => (b, As))
.Where(r => !r.As.Any())
.Select(r => r.b)
.ToList();