【发布时间】:2016-10-23 20:22:40
【问题描述】:
我创建了一个通用的extension 方法来基于一个公共列加入 2 个tables。代码如下:
public class SomeDTO<T,U>
{
public T TableA { get; set; }
public U TableB { get; set; }
}
public static class Helper
{
public static IQueryable<SomeDTO<T,U>> JoinExtension<T,U,Key>(this IQueryable<T> tableA, IQueryable<U> tableB, Expression<Func<T,Key>> columnA, Expression<Func<U,Key>> columnB)
{
return tableA.Join(tableB, columnA, columnB,(x, y) => new SomeDTO<T, U>{TableA = x,TableB = y});
}
}
现在database中的表有2个公共列(Id,Type),我需要编写一个公共扩展方法来基于2个公共列加入这些表,写了如下内容:
public static IQueryable<SomeDTO<T, U>> JoinExtensionTwoColumns<T, U, Key>(this IQueryable<T> tableA, IQueryable<U> tableB, Expression<Func<T, Key>> columnA, Expression<Func<U, Key>> columnB, Expression<Func<T, Key>> columnC, Expression<Func<U, Key>> columnD)
{
return tableA.Join(tableB, a => new { columnA, columnB }, b => new { columnC, columnD }, (a, b) => new SomeDTO<T, U> { TableA = a, TableB = b });
}
编译器在代码tableA.Join.... 行给我一个错误,如下所示:
The type arguments for method 'Queryable.Join<TOuter, TInner, TKey, TResult>(IQueryable<TOuter>, IEnumerable<TInner>, Expression<Func<TOuter, TKey>>, Expression<Func<TInner, TKey>>, Expression<Func<TOuter, TInner, TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
它无法正确理解arguments 及其性质。
任何指向我可能出错的地方?
编辑:
我现在有一个编译成功的方法,但是我得到一个运行时错误
"The LINQ expression node type 'Lambda' is not supported in LINQ to Entities."
public static IQueryable<SomeDTO<T, U>> JoinExtensionTwoColumns<T, U, Key>(this IQueryable<T> tableA, IQueryable<U> tableB, Expression<Func<T, Key>> columnA, Expression<Func<U, Key>> columnB, Expression<Func<T, Key>> columnC, Expression<Func<U, Key>> columnD)
{
return tableA.Join(tableB, a => new object[]{ columnA, columnB }, b => new object []{ columnC, columnD }, (a, b) => new SomeDTO<T, U> { TableA = a, TableB = b });
}
这样调用方法:
var result= (db.table1.JoinExtensionTwoColumns<table1,table2,int>(db.table2, c => c.id.ToString(), d => d.id.ToString(),e => e.type, f => f.type)).Take(10);
还有更多指针。
【问题讨论】:
-
您有一个匿名类型,它需要一个名称:new { columnA, columnB }(2 个位置)。您也可以使用 object 代替: new object[] { columnA, columnB } 。任何类型都会自动转换为对象,但在将类型对象分配给特定类型时需要进行转换。
-
@jdweng ..我已经尝试过你所说的。虽然没有编译器错误,但运行时错误“LINQ to Entities 不支持 LINQ 表达式节点类型 'Lambda'。”。我试图弄清楚。谢谢
-
@jdweng:请查看编辑并给出一些指示。谢谢
标签: c# entity-framework linq generics join