简体   繁体   English

需要帮助使用 EF 从多个表中获取数据

[英]Need help in getting data from multiple table using EF

I am getting details in list format using this query, in that I am also getting user id.我正在使用此查询以列表格式获取详细信息,因为我还获取了用户 ID。

reportProblemsList = objEntities.ReportProblems.ToList();

Now I want to get user details based on that user id from users table.现在我想根据用户表中的用户 ID 获取用户详细信息。 So I have tried with foreach loop as per below.所以我按照下面的方法尝试了 foreach 循环。

foreach(var item in reportProblemsList)
{
   userdetails = objEntities.Users.Where(x => x.UserId == item.Userid).ToList();
}

Now I want to add this all userdetails in list and then access it.现在我想在列表中添加所有用户详细信息,然后访问它。 Below is my full code.下面是我的完整代码。

List<ReportProblem> reportProblemsList = new List<ReportProblem>();
List<User> userdetails = new List<User>();

reportProblemsList = objEntities.ReportProblems.ToList();

foreach(var item in reportProblemsList)
{
   userdetails = objEntities.Users.Where(x => x.UserId == item.Userid).ToList();
}

reportProblemsList.Add(userdetails);

But not able to get it working..any idea.但无法让它工作......任何想法。

Thanks谢谢

I assume that you need a list users who reported the issue.我假设您需要一个报告问题的用户列表。

var userIds = objEntities.ReportProblems.Select(q=> q.Userid).ToList();
List<User> userdetails = objEntities.Users.Where(x => userIds.Contains( x.UserId)).ToList();

If you database is correctly designed from the given information, there is a high probability that your ReportProblem object has also the property User of type User .如果您根据给定的信息正确设计了数据库,则您的ReportProblem对象很可能还具有User类型的属性User If this is the case you can instruct EF core to include such nested properties in your query by doing something like this:如果是这种情况,您可以通过执行以下操作来指示 EF 核心在您的查询中包含此类嵌套属性:

var reportProblemsList = objEntities.ReportProblems
    .Include(report => report.User)
    .ToList();

If you don't have this property you have to create an anonymous type to hold the tuple:如果你没有这个属性,你必须创建一个匿名类型来保存元组:

var reportsWithUsers = objEntities.ReportProblems
    .Join(objEntities.Users, r => r.UserId, u => u.UserId, (Report, User) => (Report, User)
    .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM