使用一组Id来搜索Entity Framework表格

huangapple go评论67阅读模式
英文:

Searching Entity Framework table with a list of Id's

问题

我有一个返回Entity Framework表的函数,但我只需要通过另一个实体列表传递的特定id。我不确定正确的方法是什么,我尝试了以下方法,但列表引发了问题...

public IEnumerable<Payment> PaymentsForContact(List<User> user) =>
    _context.Payments.Where(p => user.Any(u => u.Id == p.Id));

是否可以通过迭代用户对象来仅返回_context.Payments中存在的用户id?

提前感谢。

英文:

I have a function that returns an entity framework table, but i only need certain id's which are passed in via another entity list. I'm not sure the correct way to do this, i've tried the following but the list is causing issues...

public IEnumerable&lt;Payment&gt; PaymentsForContact(List&lt;User&gt; user) =&gt; 
        _context.Payments.Where(p=&gt; p.Id == user.Id;

Is there a way i can iterate through user object to only return the id's in user that are in _context.Payments?

Thanks in advance

答案1

得分: 6

遍历两个表中的内容时,可以使用连接操作。

Payments.Join(Users, p => p.UserID, u => u.UserID, (p, u) => p)

这会返回具有用户的付款记录。

如果您已经有一个ID列表,可以使用Contains方法:

var list = new List<int> { 1, 2, 3, 4 };
Payments.Where(p => list.Contains(p.UserId));

但这仅推荐用于小型ID列表(少于100个),因为所有的ID都会成为查询字符串的一部分。

英文:

To iterate through something, that is in two tables, you use a join

Payments.Join(Users, p=&gt;p.UserID, u =&gt;u.UserID, (p,u)=&gt;p)

returns payments, that have a user.

If you already have a list of ID's than you can use Contains

var list = new List&lt;int&gt; { 1,2,3,4};
Payments.Where( p =&gt; list.Contains(p.UserId));

But this is only recommended for small lists of id (less than 100), cause all the id's become part of your query string.

答案2

得分: 2

我认为这段代码实现了你想要的功能:

_context.Payments.Where(p => user.Any(u => u.Id == p.Id));

对于每个支付项,你需要检查用户列表是否包含该支付项。

英文:

I think this code do what you want:

_context.Payments.Where(p=&gt; user.Any(u=&gt; u.Id == p.Id));

For each payment you have to check if user list contains that payment

huangapple
  • 本文由 发表于 2020年1月3日 19:09:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定