Заполнение списка типов классов, который содержит другой список типов классов из таблицы данных в c# - PullRequest
0 голосов
/ 08 января 2020

У меня есть DataTable, заполненная следующей хранимой процедурой:

CREATE PROCEDURE [dbo].[UspGetSiteLevelPendingFeedBack] 
    (@TokenID UNIQUEIDENTIFIER)
AS
BEGIN
    DECLARE @UserID UNIQUEIDENTIFIER, @LoginName NVARCHAR(255)

    EXEC [Intelligios].[UspGetSEHALoginName] 
         @TokenID = @TokenID, @LoginName = @LoginName OUTPUT

    SELECT @UserID = U.ObjectID
    FROM [User] U
    INNER JOIN UserBase UB ON U.UserBaseID = UB.ObjectID
                           AND UB.IsDeleted = 0
    WHERE U.IsDeleted = 0
      AND U.IsBanned = 0
      AND UB.LoginName = @LoginName

    SELECT
        WS.SurveyID ,
        WS.WorkID AS WorkOrderID,
        ws.IsFilled,
        WS.ObjectiD As WorkSurveyID,
        W.ObjectNumber AS WorkOrderNumber,
        W.WorkDescription,
        C.ObjectNumber AS CaseID,
        SQ.ObjectID AS SurveyQuestionnarieID,
        SQ.SurveyQuestionDescription AS QuestionDescription,
        SQ.ResponseSetID,
        SQ.ExpectedResponseSet As FeedbackType,
        SQ.IsMandatory,
        SQ.StepNumber,
        SQ.HasSingleTextboxField As IsCommentBox,
        CR.DisplayOrder,
        cr.ChecklistResponseSetID As OptionID,
        cr.ObjectName As OptionName
    FROM WorkSurvey WS
    INNER JOIN WORK W ON W.ObjectID = WS.WorkID
    INNER JOIN [Case] C ON C.ObjectID = W.CaseID
    INNER JOIN SurveyQuestionnaire SQ ON SQ.SurveyID = WS.SurveyID
                                      AND WS.IsFilled = 0 AND WS.UserID = @UserID
    LEFT JOIN ChecklistResponse CR ON CR.ChecklistResponseSetID = SQ.ResponseSetID
    ORDER BY WS.CreatedDateTime, SQ.StepNumber, CR.DisplayOrder
END

У меня есть таблица WorkSurvey, в которой хранятся данные, соответствующие каждому рабочему заданию, и для каждого WorkSurvey может быть I или больше вопросов в таблице SurveyQuestionnaire, и для каждого вопроса может быть несколько вариантов выбора, которые хранятся в таблице ChecklistResponse.

Таким образом, используя вышеописанную хранимую процедуру, я получил требуемые данные и с целью создание API, я создал сущности, как показано ниже.

public partial class WorkOrderFeedbackDetails
{
        public Guid? WorkOrderID { get; set; }
        public Guid? WorkSurveyID { get; set; }
        public string WorkOrderNumber { get; set; }
        public string WorkDescription { get; set; }
        public string CaseID { get; set; }
        public Guid? SurveyID { get; set; }
        public  List<Questions> Feedbackquestions { get; set; }
}

public partial class Questions
{
        public Guid? SurveyQuestionnarieID { get; set; }
        public string QuestionDescription { get; set; }
        public Guid? ResponseSetID { get; set; }
        public int? FeedBackType { get; set; }
        public int? IsMandatory { get; set; }
        public int? StepNumber { get; set; }
        public int? IsCommentBox { get; set; }
        public Guid? SurveyID { get; set; }
        public List<Options> Options { get; set; }
}

public partial  class Options
{
        public int? DisplayOrder { get; set; }
        public Guid? OptionID { get; set; }
        public string OptionName { get; set; }
        public Guid? ResponseSetID { get; set; }
}

public partial class  FeedbackDetails
{
        public Guid? WorkOrderID { get; set; }
        public Guid? WorkSurveyID { get; set; }
        public string WorkOrderNumber { get; set; }
        public string WorkDescription { get; set; }
        public string CaseID { get; set; }
        public Guid? SurveyQuestionnarieID { get; set; }
        public string QuestionDescription { get; set; }
        public Guid? ResponseSetID { get; set; }
        public int? FeedBackType { get; set; }
        public int? IsMandatory { get; set; }
        public int? StepNumber { get; set; }
        public int? IsCommentBox { get; set; }
        public int? DisplayOrder { get; set; }
        public Guid? OptionID { get; set; }
        public string OptionName { get; set; }
        public Guid? SurveyID { get; set; }
}

Ниже приведен код, который я использовал для заполнения списка типов или типов классов

public List<Entities.WorkOrderFeedbackDetails> GetPendingFeedBack2(Entities.Shared.Requests.BaseRequest baseRequest)
{
        Database db = new Database();
        List<Entities.FeedbackDetails> FeedBackDetailList = new List<FeedbackDetails>();
        List<Entities.WorkOrderFeedbackDetails> workOrders   = new List<WorkOrderFeedbackDetails>();

        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = @"[dbo].[UspGetSiteLevelPendingFeedBack]";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@TokenID", SqlDbType.UniqueIdentifier).Value = baseRequest.tokenId;

                DataSet ds = new DataSet();
                ds = db.ExecuteProc(cmd);
                if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        Entities.FeedbackDetails feedback = new Entities.FeedbackDetails
                        {
                            //Case Details
                            SurveyID = db.GetGuidValue(dr, "SurveyID"),
                            WorkOrderID = db.GetGuidValue(dr, "WorkOrderID"),
                            WorkSurveyID = db.GetGuidValue(dr, "WorkSurveyID"),
                            WorkOrderNumber = db.GetStringValue(dr, "WorkOrderNumber"),
                            WorkDescription = db.GetStringValue(dr, "WorkDescription"),
                            CaseID = db.GetStringValue(dr, "CaseID"),
                            SurveyQuestionnarieID = db.GetGuidValue(dr, "SurveyQuestionnarieID"),
                            QuestionDescription = db.GetStringValue(dr, "QuestionDescription"),
                            ResponseSetID = db.GetGuidValue(dr, "ResponseSetID"),
                            FeedBackType = db.GetIntValue(dr, "FeedbackType"),
                            IsMandatory = db.GetIntValue(dr, "IsMandatory"),
                            StepNumber = db.GetIntValue(dr, "StepNumber"),
                            IsCommentBox = db.GetIntValue(dr, "IsCommentBox"),
                            DisplayOrder = db.GetIntValue(dr, "DisplayOrder"),
                            OptionID = db.GetGuidValue(dr, "OptionID"),
                            OptionName = db.GetStringValue(dr, "OptionName")
                        };
                        FeedBackDetailList.Add(feedback);
                    }

                    if (FeedBackDetailList.Count == 0)
                    {
                        FeedBackDetailList = null;
                    }

                    workOrders = FeedBackDetailList.Select(a => new WorkOrderFeedbackDetails()
                    {
                        WorkOrderID = a.WorkOrderID,
                        WorkDescription = a.WorkDescription,
                        WorkOrderNumber = a.WorkOrderNumber,
                        WorkSurveyID = a.WorkSurveyID,
                        CaseID = a.CaseID,
                        SurveyID = a.SurveyID,
                        Feedbackquestions = FeedBackDetailList.Where(b => b.SurveyID == a.SurveyID).
                           Select(c => new Questions()
                           {
                               SurveyQuestionnarieID = c.SurveyQuestionnarieID,
                               QuestionDescription = c.QuestionDescription,
                               ResponseSetID = c.ResponseSetID,
                               FeedBackType = c.FeedBackType,
                               IsMandatory = c.IsMandatory,
                               StepNumber = c.StepNumber,
                               IsCommentBox = c.IsCommentBox,
                               SurveyID = c.SurveyID,
                               Options=FeedBackDetailList.Where(d=>d.ResponseSetID==c.ResponseSetID).
                               Select(e=>new Options()
                               {
                                   OptionID = e.OptionID,
                                   ResponseSetID = e.ResponseSetID,
                                   DisplayOrder = e.DisplayOrder,
                                   OptionName = e.OptionName
                               }).ToList<Options>()
                           }).ToList<Questions>()
                    }).Distinct().ToList<WorkOrderFeedbackDetails>();
                }
            }
        }
        catch (Exception ex)
        {
            db.LogError(new CommonEntities.ErrorLog
            {
                errorTitle = System.Reflection.MethodBase.GetCurrentMethod().Name,
                reportedDateTime = DateTime.Now,
                tokenId = baseRequest.tokenId,
                errorDescription = ex.ToString()
            });
        }
        return workOrders;
    }

Это правильный способ сделать выше, чтобы сгенерировать json формат, как показано ниже

[
   {
      "workOrderId":"647657ffgddfd55e67",
      "workOrderNumber":"TWM-CM-1911-00002",
      "workOrderDesc":"Work Order description description description description description description",
      "caseId":"CR-TWM-00001",
      "feedback":[
         {
            "isCommentBox":true,
            "feedbackType":0,
            "questionList":[
               {
                  "question":"Is there any way to have a label wordwrap text as needed? I have the line breaks set to word wrap and the label is tall enough for two lines, but it appears that it will only wrap on line breaks. Do I have to add line breaks to make it wrap properly?",
                  "optionList":[
                     {
                        "optionId":"1",
                        "optionName":"Option 1 s there any way to have a label wordwrap text as needed? I have the line breaks",
                        "isSelected":true
                     },
                     {
                        "optionId":"2",
                        "optionName":"Option 2",
                        "isSelected":false
                     }
                  ]
               }
            ],
            "comment":"Any comments"
         },
         {
            "isCommentBox":true,
            "comment":"Any comments",
            "feedbackType":1,
            "question":"Question 1",
            "reply":"Reply to Question 1 in multiline"
         },
         {
            "isCommentBox":true,
            "comment":"Any comments",
            "feedbackType":2,
            "question":"Question 1",
            "reply":"Reply to Question 1 in single line"
         },
         {
            "isCommentBox":true,
            "comment":"Any comments",
            "feedbackType":3,
            "questionList":[
               {
                  "question":"Question 1",
                  "optionList":[
                     {
                        "optionId":"1",
                        "optionName":"Option 1",
                        "isSelected":true
                     }
                  ]
               }
            ]
         }
      ]
   },
   {
      "workOrderId":"647657ffgddfd55e67",
      "workOrderNumber":"TWM-CM-1911-00003",
      "workOrderDesc":"Work Order description description description description description description",
      "caseId":"CR-TWM-00002",
      "feedback":[
         {
            "isCommentBox":true,
            "feedbackType":0,
            "questionList":[
               {
                  "question":"Is there any way to have a label wordwrap text as needed? I have the line breaks set to word wrap and the label is tall enough for two lines, but it appears that it will only wrap on line breaks. Do I have to add line breaks to make it wrap properly?",
                  "optionList":[
                     {
                        "optionId":"1",
                        "optionName":"Option 1 s there any way to have a label wordwrap text as needed? I have the line breaks",
                        "isSelected":true
                     },
                     {
                        "optionId":"2",
                        "optionName":"Option 2",
                        "isSelected":false
                     }
                  ]
               }
            ],
            "comment":"Any comments"
         },
         {
            "isCommentBox":true,
            "comment":"Any comments",
            "feedbackType":1,
            "question":"Question 1",
            "reply":"Reply to Question 1 in multiline"
         },
         {
            "isCommentBox":true,
            "comment":"Any comments",
            "feedbackType":2,
            "question":"Question 1",
            "reply":"Reply to Question 1 in single line"
         },
         {
            "isCommentBox":true,
            "comment":"Any comments",
            "feedbackType":3,
            "questionList":[
               {
                  "question":"Question 1",
                  "optionList":[
                     {
                        "optionId":"1",
                        "optionName":"Option 1",
                        "isSelected":true
                     }
                  ]
               }
            ]
         }
      ]
   }
]

1 Ответ

0 голосов
/ 11 января 2020

Вот как я сделал метод, и я получаю результат в соответствии с требованиями.

     public List<Entities.WorkOrderFeedbackDetails> GetPendingFeedBack(Entities.Shared.Requests.BaseRequest baseRequest)
        {
            Database db = new Database();

            List<Entities.WorkOrderFeedbackDetails> workOrders = new List<WorkOrderFeedbackDetails>();


            try
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = @"[dbo].[UspGetSiteLevelPendingFeedBack]";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@TokenID", SqlDbType.UniqueIdentifier).Value = baseRequest.tokenId;

                    DataSet ds = new DataSet();
                    ds = db.ExecuteProc(cmd);
                    if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                    {

                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            Entities.WorkOrderFeedbackDetails feedback = new Entities.WorkOrderFeedbackDetails
                            {
                                //Case Details

                                WorkOrderID = db.GetGuidValue(dr, "WorkOrderID"),
                                WorkSurveyID = db.GetGuidValue(dr, "WorkSurveyID"),
                                WorkOrderNumber = db.GetStringValue(dr, "WorkOrderNumber"),
                                WorkDescription = db.GetStringValue(dr, "WorkDescription"),
                                CaseID = db.GetStringValue(dr, "CaseID"),
                                SurveyID = db.GetGuidValue(dr, "SurveyID"),

                            };

                            foreach (DataRow dr2 in ds.Tables[0]
                                .Select("WorkOrderID = '" + db.GetGuidValue(dr, "WorkOrderID") + "'" +
                                " AND WorkSurveyID='" + db.GetGuidValue(dr, "WorkSurveyID") + "'"))
                            {
                                Entities.Questions questions = new Questions
                                {
                                    SurveyQuestionnarieID = db.GetGuidValue(dr2, "SurveyQuestionnarieID"),
                                    QuestionDescription = db.GetStringValue(dr2, "QuestionDescription"),
                                    ResponseSetID = db.GetGuidValue(dr2, "ResponseSetID"),
                                    FeedBackType = db.GetIntValue(dr2, "FeedbackType"),
                                    IsMandatory = db.GetIntValue(dr2, "IsMandatory"),
                                    StepNumber = db.GetIntValue(dr2, "StepNumber"),
                                    IsCommentBox = db.GetIntValue(dr2, "IsCommentBox"),
                                    SurveyID = db.GetGuidValue(dr2, "SurveyID")

                                };

                                foreach (DataRow dr3 in ds.Tables[0]
                               .Select("SurveyQuestionnarieID='" + db.GetGuidValue(dr2, "SurveyQuestionnarieID") + "'"))
                                {
                                    Entities.Options options = new Options
                                    {
                                        DisplayOrder = db.GetIntValue(dr3, "DisplayOrder"),
                                        OptionID = db.GetGuidValue(dr3, "OptionID"),
                                        OptionName = db.GetStringValue(dr3, "OptionName"),
                                        ResponseSetID = db.GetGuidValue(dr3, "ResponseSetID"),
                                        ChecklistResponseSetID = db.GetGuidValue(dr3, "ChecklistResponseSetID")
                                    };
                                  //  if (!questions.Options.Any(item => item.OptionID == options.OptionID))
                                        questions.Options.Add(options);

                                }
                                if (!feedback.Feedbackquestions.Any(item => item.SurveyQuestionnarieID == questions.SurveyQuestionnarieID))
                                    feedback.Feedbackquestions.Add(questions);
                            }


                                if (!workOrders.Any(item => item.WorkSurveyID == feedback.WorkSurveyID))
                                workOrders.Add(feedback);



                        }
                        if (workOrders.Count == 0)
                        {
                            workOrders = null;
                        }


                    }
                }
            }
            catch (Exception ex)
            {
                db.LogError(new CommonEntities.ErrorLog
                {
                    errorTitle = System.Reflection.MethodBase.GetCurrentMethod().Name,
                    reportedDateTime = DateTime.Now,
                    tokenId = baseRequest.tokenId,
                    errorDescription = ex.ToString()
                });
            }
            return workOrders;
        }

...