英文:
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<Payment> PaymentsForContact(List<User> user) =>
_context.Payments.Where(p=> 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=>p.UserID, u =>u.UserID, (p,u)=>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<int> { 1,2,3,4};
Payments.Where( p => 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=> user.Any(u=> u.Id == p.Id));
For each payment you have to check if user list contains that payment
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论