Sri*_*har 2 .net c# linq generics linq-to-sql
我正在尝试在泛型中编写 LINQ 连接查询,但在识别外键时遇到问题。PFB 代码。
我想识别表 U 中存在的外键,我可以将其用于比较操作。谢谢
var _tab = (from tblT in context.GetTable<T>()
join tblU in context.GetTable<U>()
on pk equals fk
select tblT).GetEnumerator();
Run Code Online (Sandbox Code Playgroud)
您提到要“识别表 U 中存在的外键”。虽然您可以通过反射和某种约定来做到这一点,但这似乎是一个脆弱的解决方案。我建议您通过委托提供主/外键关系。
基本上,联接使用委托来检索主键和外键,并且 LINQ 提供程序将其转换为联接子句。连接每一侧的签名基本相同,在您的示例中它将是:Expression<Func<T, TKey>>和Expression<Func<U, TKey>>。需要注意的是,连接两端的键类型必须相同。
无论您使用什么来调用此方法,都应该要求传入这些委托。它可能如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
调用它看起来像这样:
var data = query.GetData<Person, Order, int>(person => person.Id, order => order.Orderer.Id);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1675 次 |
| 最近记录: |