我正在尝试用泛型编写 LINQ 连接查询,但在识别外键时遇到了问题。 PFB代码。
我想识别表U中存在的外键,我可以用它来进行比较操作。谢谢
var _tab = (from tblT in context.GetTable<T>()
join tblU in context.GetTable<U>()
on pk equals fk
select tblT).GetEnumerator();
最佳答案
您提到您想要“识别表 U 中存在的外键”。虽然您可以通过反射和某种约定来做到这一点,但这似乎是一个脆弱的解决方案。我建议您通过委托(delegate)提供主键/外键关系。
基本上,连接使用委托(delegate)来检索主键和外键,LINQ 提供程序将其转换为连接子句。连接每一方的签名基本相同,在您的示例中为:Expression<Func<T, TKey>>
和 Expression<Func<U, TKey>>
.请务必注意,连接两侧的 key 类型必须相同。
无论您使用什么来调用此方法,都应该要求传入这些委托(delegate)。它可能看起来像这样:
public class Query
{
public IEnumerable<T> GetData<T, U, TKey>(Expression<Func<T, TKey>> tKey, Expression<Func<U, TKey>> uKey)
{
Context context = new Context();
// using the extension method as the query expression had trouble figuring out the types
var data = context.GetTable<T>().Join(context.GetTable<U>(), tKey, uKey, (tblT, tblU) => tblT);
return data;
}
}
调用它看起来像这样:
var data = query.GetData<Person, Order, int>(person => person.Id, order => order.Orderer.Id);
关于c# - 使用泛型的 LINQ 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14006442/