如何在 dotnet core 中使用实体框架获取数据 [英] How to Data Fetch using Entity Framework in dotnet core

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

问题描述

我有一个名为UserAnswers"的表.下面的屏幕截图包含表数据

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

我想按surveyId获取数据并按CreatedBy列分组.

I want to get data by surveyId and group by CreatedBy column.

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

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 中使用实体框架获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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