如何在dotnet core中使用Entity Framework进行数据获取 [英] How to Data Fetch using Entity Framework in dotnet core

查看:104
本文介绍了如何在dotnet core中使用Entity Framework进行数据获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 UserAnswers的表。以下屏幕快照包含表数据
< img src = https://i.stack.imgur.com/mlhCP.png alt =在此处输入图片描述>

I have a table called "UserAnswers".below screenshot contains table data

我要

例如
有一个名为 amara@gmail.com的用户。该用户包含4记录为SurveyId。
我想像下面这样

for an example There is a user called "amara@gmail.com".this user contains 4 records for a SurveyId. I want to get this like below

Answers : [
            {"2"},
            {"1","0","1","1"},
            {"1","2","4","3"},
            {"Blue"}] 

但是我的代码为每一行返回此数组。我的意思是返回重复的记录。

But my code returns this array for every rows.I meant duplicate records returning.

这是我的代码

 var qstns = await (from uans in _context.UserAnswers
                                       where uans.SurveyId == id
                                       select new UserAnswersReturnDto
                                       {
                                           UserEmail = uans.CreatedBy,
                                           Qustns = (from ans in _context.UserAnswers
                                                      where ans.CreatedBy == uans.CreatedBy 
                                                      select new UserAnswersSet
                                           {
                                               QNo = ans.QNo,
                                               Ansrs = JsonConvert.DeserializeObject<JArray>(string.IsNullOrEmpty(ans.Answers) ? "[]" : ans.Answers)
                                           }).ToArray() 

                                       }).ToListAsync();

如何解决这个问题。我为此问题开了很多问题,但没人回答。谢谢。

So how to solve this issue.I opened many questions for this problem,but no one answered.Please help me.Thanks in advanced

推荐答案

您需要对数据进行实际分组,然后返回:

You need to actually group your data before returning:

我使用LINQ Lambda表示法,但是如果您愿意,应该可以很容易地将其转换回查询:

I used LINQ Lambda notation, but it should be quite easy to translate back to query if you're so inclined:

var qstns = _context.UserAnswers.Where(uans => uans.SurveyId == id)
                                .GroupBy(uans => uans.CreatedBy)
                                .Select(grans => new UserAnswersReturnDto {
                                    UserEmail = grans.Key,
                                    Qustions = grans.Select(ans => new UserAnswersSet() {
                                        QNo = ans.QNo,
                                        Ansrs = ans.Answers
                                    }).ToList()
                                } ).ToList();

我没有时间仔细检查这一点,但我希望它能为您提供指导帮助您解决问题!

I didn't have time to double-check this, but I hope it serves as a guide to help you solve your issue!

这篇关于如何在dotnet core中使用Entity Framework进行数据获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆