Moon.Orm 5.0 (MQL版) 实战实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gta.Exam.Entities;
using Moon.Orm;
using System.Web;
using Gta.Exam.Utilities;
using System.Data.Common;

namespace Gta.Exam.BLL
{
     public  class QuestionBLL
    {
         private  static  readonly log4net.ILog LOG_ERROR = log4net.LogManager. GetLogger( typeof(QuestionBLL));
         /// <summary>
         /// 根据试题ID 返回试题数据
         /// </summary>
         public  static QuestionViewResult  GetQuestionResult( int questionId)
        {
            QuestionViewResult qr =  new  QuestionViewResult();
             using (Db db = Db. CreateDefaultDb())
            {
                 var MQL = QuestionViewSet. SelectAll()
                    . Where(QuestionViewSet.Id. Equal(questionId));
                qr = db.GetEntity<QuestionViewResult>(MQL);
            }

             return qr;
        }

         /// <summary>
         /// 根据父级ID 获取子试题列表
         /// </summary>
         /// <param name="questionId"></param>
         /// <returns></returns>
         public List<QuestionViewResult>  GetChildQuestions( int questionId)
        {
            List<QuestionViewResult> qr =  new List<QuestionViewResult>();
             using (Db db = Db. CreateDefaultDb())
            {
                 var MQL = QuestionViewSet. SelectAll()
                    . Where(QuestionViewSet.ParentId. Equal(questionId));

                qr = db.GetEntities<QuestionViewResult>(MQL);
            }

             return qr;
        }

         /// <summary>
         /// 我上传的试题
         /// </summary>
         public List<QuestionViewResult>  MyUpload( int? page,  int? rows,  string sort,  string order, Question que,  out  int recordCount,  int User_Id)
        {
            List<QuestionViewResult> data;

            EntityBase et =  new  EntityBase();

            WhereExpression  where = QuestionViewSet.Status. NotEqual( 5) //不作废
                . And(QuestionViewSet.ParentId. Equal( 0))
                . And(QuestionViewSet.IsExtract. Equal(que.IsExtract))
                . And(QuestionViewSet.UserId. Equal(User_Id))
                . And(QuestionViewSet.CourseId. Equal(que.CourseId));
             if (! string. IsNullOrEmpty(que.KnowledgeId) && que.KnowledgeId !=  "0")
            {
                 where =  where. And(QuestionViewSet.KnowledgeId. Contains(que.KnowledgeId));
            }
             if (que.QuestionType >  0)
            {
                 where =  where. And(QuestionViewSet.QuestionType. Equal(que.QuestionType));
            }
             if (que.Difficulty >  0)
            {
                 where =  where. And(QuestionViewSet.Difficulty. Equal(que.Difficulty));
            }
             //未共享的 (包含 待审核 以及 审核不通过的)
             if (que.Status ==  1)
            {
                 where =  where. And(QuestionViewSet.Status. NotEqual( 4));
            }
             else  if (que.Status >  0)
            {
                 where =  where. And(QuestionViewSet.Status. Equal(que.Status));
            }

            data =  GetList(page, rows, sort, order,  out recordCount,  where);
             return data;
        }

         /// <summary>
         /// 公共试题
         /// </summary>
         public List<QuestionViewResult>  Public( int? page,  int? rows,  string sort,  string order, Question que,  out  int recordCount)
        {
            List<QuestionViewResult> data;

            EntityBase et =  new  EntityBase();

            WhereExpression  where = QuestionViewSet.Status. Equal( 4) //共享试题
                . And(QuestionViewSet.ParentId. Equal( 0))
                . And(QuestionViewSet.CourseId. Equal(que.CourseId));
             if (! string. IsNullOrEmpty(que.KnowledgeId) && que.KnowledgeId !=  "0")
            {
                 where =  where. And(QuestionViewSet.KnowledgeId. Contains(que.KnowledgeId));
            }
             if (que.QuestionType >  0)
            {
                 where =  where. And(QuestionViewSet.QuestionType. Equal(que.QuestionType));
            }
             if (que.Difficulty >  0)
            {
                 where =  where. And(QuestionViewSet.Difficulty. Equal(que.Difficulty));
            }

            data =  GetList(page, rows, sort, order,  out recordCount,  where);
             return data;
        }

         /// <summary>
         /// 我收藏的试题
         /// </summary>
         public List<QuestionViewResult>  MyFavorite( int? page,  int? rows,  string sort,  string order, Question que,  out  int recordCount,  int User_Id)
        {
            List<QuestionViewResult> data;

            EntityBase et =  new  EntityBase();

            WhereExpression  where = QuestionViewSet.Status. Equal( 4) //共享的
                . And(QuestionViewSet.ParentId. Equal( 0))
                . And(QuestionViewSet.CourseId. Equal(que.CourseId));
             where =  where. And(QuestionViewSet.Id. In(
                QuestionCollectionSet. Select(QuestionCollectionSet.QuestionId)
                . Where(QuestionCollectionSet.UserId. Equal(User_Id))));
             if (! string. IsNullOrEmpty(que.KnowledgeId) && que.KnowledgeId !=  "0")
            {
                 where =  where. And(QuestionViewSet.KnowledgeId. Contains(que.KnowledgeId));
            }
             if (que.QuestionType >  0)
            {
                 where =  where. And(QuestionViewSet.QuestionType. Equal(que.QuestionType));
            }
             if (que.Difficulty >  0)
            {
                 where =  where. And(QuestionViewSet.Difficulty. Equal(que.Difficulty));
            }

            data =  GetList(page, rows, sort, order,  out recordCount,  where);
             return data;
        }

         /// <summary>
         /// 获取分页数据
         /// </summary>
         /// <param name="page">页码</param>
         /// <param name="rows">条数</param>
         /// <param name="sort">排序字段</param>
         /// <param name="order">排序</param>
         /// <param name="recordCount">总条数</param>
         /// <returns>数据列表</returns>
         public List<QuestionViewResult>  GetList( int? page,  int? rows,  string sort,  string order,  out  int recordCount, WhereExpression  where)
        {
            List<QuestionViewResult> data;

             int pageIndex = page.HasValue && page.Value >  1 ? page.Value :  1; //页数
             int pageSize = rows.HasValue && rows.Value >  1 ? rows.Value :  20; //每页条数
             int startNum = (pageIndex -  1) * pageSize; //过滤掉的条数

             var NotInId = QuestionViewSet. Select(QuestionViewSet.Id). Where( where). Top(startNum);
            NotInId =  OrderByMQL(order, NotInId,  GetOrderByField(sort));

             using (Db db = Db. CreateDefaultDb()) //默认数据库链接
            {
                db.DebugEnabled =  true; //开启调试
                recordCount = Convert. ToInt32(db. GetCount( where)); //获取总条数

                 var strSql = QuestionViewSet. SelectAll()
                    . Where( where. And(QuestionViewSet.Id. NotIn(NotInId))). Top(pageSize);
                strSql =  OrderByMQL(order, strSql,  GetOrderByField(sort));

                data = db.GetEntities<QuestionViewResult>(strSql);

                 string sql = db.CurrentSQL;
            }

             return data;
        }

         /// <summary>
         /// 返回排序的组合
         /// </summary>
         public MQLBase  OrderByMQL( string sort, MQLBase mql,  params FieldBase[] fields)
        {
             if (! string. IsNullOrEmpty(sort) && sort. ToLower() ==  "asc")
            {
                mql. OrderByASC(fields);
            }
             else
            {
                mql. OrderByDESC(fields);
            }

             return mql;
        }

         /// <summary>
         /// 排序的字段
         /// </summary>
         public FieldBase  GetOrderByField( string order)
        {
            FieldBase result =  null;
             switch (order)
            {
                 case  "Id":
                    result = QuestionViewSet.Id;
                     break;
                 case  "KnowledgeName":
                    result = QuestionViewSet.KnowledgeId;
                     break;
                 case  "Question_Type":
                 case  "QuestionTypeName":
                    result = QuestionViewSet.QuestionType; //试卷类型
                     break;
                 case  "Difficulty":
                 case  "DifficultName":
                    result = QuestionViewSet.Difficulty; //试题难度
                     break;
                 case  "Score":
                    result = QuestionViewSet.Score; //分数
                     break;
                 case  "Create_Date":
                 case  "CreateTimeString":
                    result = QuestionViewSet.CreateDate; //创建时间
                     break;
                 case  "StatusName":
                    result = QuestionViewSet.Status; //共享状态
                     break;
                 case  "CollectCount":
                    result = QuestionViewSet.CollectCount; //收藏量
                     break;
                 case  "UseCount":
                    result = QuestionViewSet.UseCount; //使用量
                     break;
                 case  "UserName":
                    result = QuestionViewSet.UserId;
                     break;
                 default:
                    result = QuestionViewSet.CreateDate; //创建时间
                     break;
            }

             return result;
        }

         public  static  bool  ChangeMoreQuestionStatus( string questionStringIDs,  bool isPass)
        {
             int count =  0;
             using (Db db = Db. CreateDefaultDb())
            {
                Question questionentity =  new  Question();
                questionentity.Status = isPass ? ( byte)QuestionStatusEnum.SharedToAuditSuccess : ( byte)QuestionStatusEnum.SharedToAuditFail;
                questionentity.WhereExpression = QuestionSet.Id. In(questionStringIDs. Split( ','));
                 //WhereExpression where = QuestionSet.Status.Equal(questionentity.Status).And(QuestionSet.Id.In(questionStringIDs.Split(',')));
                 //var strSql = QuestionSet.SelectAll().Where(where);
                 //string sql = strSql.ToDebugSQL();
                count = db. Update(questionentity);
            }
             if (count >  0)
                 return  true;
             else
                 return  false;
        }

         /// <summary>
         ///更改status状态 私有试题(1)、共享待审核(2)、审核不通过(3)、公有试题(4)、作废(5)
         /// </summary>
         public  static  bool  DeleteQuestion( int ID,  int Status)
        {
             bool result =  false;
             if (ID >  0)
            {
                 using (Db db = Db. CreateDefaultDb())
                {
                    Question que =  new  Question();
                    que.Status = ( byte)Status;
                    que.WhereExpression = QuestionSet.Id. Equal(ID);
                    result = db. Update(que) >  0 ?  true :  false;
                }
            }
             return result;
        }

         /// <summary>
         /// 获取分页数据
         /// </summary>
         /// <param name="page">页码</param>
         /// <param name="rows">条数</param>
         /// <param name="sort">排序字段</param>
         /// <param name="order">排序</param>
         /// <param name="searchEntity">查询实体条件</param>
         /// <param name="recordCount">总条数</param>
         /// <returns>数据列表</returns>
         public List<QuestionViewResult>  QuestionAuditList( int? page,  int? rows,  string sort,  string order, Question searchEntity,  out  int recordCount)
        {
            List<QuestionViewResult> data;

            WhereExpression  where = QuestionViewSet.Status. Equal(searchEntity.Status);

             if (searchEntity.Id >  0)
            {
                 where =  where. And(QuestionViewSet.Id. In(searchEntity.Id));
            }

            data =  GetList(page, rows, sort, order,  out recordCount,  where);
             return data;
        }


         #region 创建试题

         /// <summary>
         /// 创建多个问题
         /// </summary>
         /// <param name="qpModelList"></param>
         /// <returns></returns>
         public OperationResult  CreateMoreQuestion(IEnumerable<QuestionProduceModel> qpModelList)
        {
             if (qpModelList ==  null)
            {
                 throw  new  ArgumentNullException( "qpModel");
            }
            OperationResult operation =  new  OperationResult();
             foreach ( var item  in qpModelList)
            {
                ResultMessage result =  CreateQuestion(item);
                 if (result.Success)
                {
                    operation.SuccessCount++;
                }
                 else
                {
                    operation.FailureCount++;
                }
            }
             return operation;
        }

         /// <summary>
         /// 创建试题
         /// </summary>
         /// <param name="qpModel"></param>
         /// <returns></returns>
         public ResultMessage  CreateQuestion(QuestionProduceModel qpModel)
        {
            ResultMessage msg =  new  ResultMessage( true"");
             if (qpModel ==  null)
            {
                 throw  new  ArgumentNullException( "qpModel");
            }
             if (qpModel.QuestionClientPostModel ==  null || !qpModel.QuestionClientPostModel. Any())
            {
                 return  new  ResultMessage( false"答题卡里面至少包含一项!");
            }
             int q_count = qpModel.QuestionClientPostModel.Length;

            Question rootQuestion;
             try
            {
                 using (Db db = Db. CreateDefaultDb())
                {
                     try
                    {
                        db.TransactionEnabled =  true;
                        ResultMessage result =  CreateQuestion(
                                            db,
                                            qpModel.QuestionClientPostModel,
                                            qpModel.Description,
                                            q_count >  1,
                                            qpModel.CourseId,
                                            qpModel.KnowledgeId,
                                            qpModel.Custom_Question_TypeId,
                                            qpModel.DifficultyId,
                                            qpModel.Creator,
                                            qpModel.Creator_Name,
                                             true,
                                             out rootQuestion);

                         //db.Transaction.Commit();
                        msg = result;
                    }
                     catch (Exception ex)
                    {
                        LOG_ERROR. Error( "添加试卷发生异常,异常信息:" + ex.Message);
                        db.Transaction. Rollback();
                    }
                }
            }
             catch (Exception)
            {
                msg =  new  ResultMessage( false"添加时发生异常,已经回滚!");
            }
             return msg;
        }

         /// <summary>
         /// 添加试题
         /// </summary>
         public ResultMessage  CreateQuestion(Db db, QuestionModelForClientPost[] clientPostQuestionModels,  string qDescription,  bool hasChildQuestion,  string courseId,  string knowledgeId,  short? custom_Question_Type,  int? difficultyId,  int creator,  string creator_Name,  bool is_Extract,  out Question rootQuestion)
        {
             #region 查看重复
             if (! string. IsNullOrEmpty(qDescription))
            {
                 //查看 课程ID 用户ID 题干内容  是否同时存在 重复数据
                WhereExpression  where = QuestionSet.UserId. Equal(creator)
                    . And(QuestionSet.CourseId. Equal(courseId))
                    . And(QuestionSet.Id. In(QuestionDescSet. Select(QuestionDescSet.QuestionId)
                        . Where(QuestionDescSet.Description. Equal(qDescription))));

                 int existsQuestionCount = Convert. ToInt32(db. GetCount( where));

                 if (existsQuestionCount >  0)
                {
                    rootQuestion =  null;
                     return  new  ResultMessage( false"添加失败!该试题已经在您的题库中存在了!");
                }
            }
             #endregion

            RealQuestionType rqType = hasChildQuestion ?
                RealQuestionType.CP : RealQuestionTypeManager. GetRealQuestionTypeByCustomKey(clientPostQuestionModels[ 0].Type);
             bool is_Machine =  true;
             decimal totalScore =  0;

             foreach (QuestionModelForClientPost item  in clientPostQuestionModels)
            {
                totalScore += item.ScoreArray. Sum();
                 if (RealQuestionTypeManager. GetRealQuestionTypeByCustomKey(item.Type) == RealQuestionType.QA)
                {
                    is_Machine =  false;
                }
            }

             string reference_Answer =  null;
             if (!hasChildQuestion && (rqType == RealQuestionType.SS || rqType == RealQuestionType.MS || rqType == RealQuestionType.RW))
            {
                 // 用逗号连接每个正确答案的选项
                 if (clientPostQuestionModels[ 0].StandardAnswer !=  null)
                {
                     if (rqType == RealQuestionType.RW)
                    {
                         string standardAnswerValue = clientPostQuestionModels[ 0].StandardAnswer[ 0];
                        reference_Answer = standardAnswerValue. Equals( "right", StringComparison.InvariantCultureIgnoreCase) ?  "1" :  "2";
                    }
                     else
                    {
                        reference_Answer =  string. Join( ",",
                            EnglishCharConverter. ConvertEnglishCharArrayToNumberArray(clientPostQuestionModels[ 0].StandardAnswer));
                    }
                }
            }

            rootQuestion =  new  Question();
             if (knowledgeId !=  null)
            {
                rootQuestion.KnowledgeId = knowledgeId;
            }
            rootQuestion.CourseId = courseId;
             if (custom_Question_Type.HasValue)
            {
                rootQuestion.CustomQuestionType = custom_Question_Type;
            }
             if (difficultyId.HasValue)
            {
                rootQuestion.Difficulty = difficultyId;
            }
            rootQuestion.QuestionType = ( short)rqType;
            rootQuestion.Score = ( double)totalScore;
            rootQuestion.QuestionSource =  0;
            rootQuestion.IsMachineScore = ( byte)(is_Machine ?  1 :  0);
            rootQuestion.ParentId =  0;
            rootQuestion.ScoreRate =  0;
            rootQuestion.Status = ( byte)QuestionStatusEnum.UnShared;
            rootQuestion.ReferenceId =  0;
             //rootQuestion.DescriptionDir = null;
            rootQuestion.CreateDate = DateTime.Now;
            rootQuestion.UserId = creator;
             if (creator_Name !=  null)
            {
                rootQuestion.UserName = creator_Name;
            }
            rootQuestion.UseCount =  0;
            rootQuestion.CollectCount =  0;
            rootQuestion.IsExtract = is_Extract ? ( byte)QuestionIsExtractEnum.Yes : ( byte)QuestionIsExtractEnum.No;
            rootQuestion.IsAnswerable = !hasChildQuestion ? ( byte) 1 : ( byte) 0;
             if (reference_Answer !=  null)
            {
                rootQuestion.ReferenceAnswer = reference_Answer;
            }

            db. Add(rootQuestion);
             //rootQuestion.Id = this._questionRepository.DeferInsertReturnNewId(rootQuestion, unitOfWork);

             if (rootQuestion.Id ==  0)
            {
                 return  new  ResultMessage( false"添加失败!未知原因!");
            }

             //添加题干
            QuestionDesc question_Desc =  new  QuestionDesc();
            question_Desc.QuestionId = rootQuestion.Id;
             if (! string. IsNullOrEmpty(qDescription))
            {
                question_Desc.Description = qDescription;
            }

            db. Add(question_Desc);

             if (hasChildQuestion)
            {
                 InsertChildQuestion(
                    db,
                    clientPostQuestionModels,
                    courseId,
                    knowledgeId,
                    custom_Question_Type,
                    difficultyId,
                    creator,
                    creator_Name,
                    rootQuestion
                    );
            }
             else
            {
                 CreateQuestionOptionToDb(
                    db,
                    clientPostQuestionModels[ 0],
                    rootQuestion,
                    rqType);
            }
             return  new  ResultMessage( true"添加成功!");
        }

         /// <summary>
         /// 添加子题
         /// </summary>
         public  void  InsertChildQuestion(Db db, QuestionModelForClientPost[] clientPostQuestionModels,  string courseId,  string knowledgeId,  short? custom_Question_Type,  int? difficultyId,  int creator,  string creator_Name, Question parentQuestion)
        {
             if (clientPostQuestionModels ==  null)
            {
                 throw  new  ArgumentNullException( "clientPostQuestionModels");
            }
             foreach (QuestionModelForClientPost item  in clientPostQuestionModels)
            {
                 var tempRqType = RealQuestionTypeManager. GetRealQuestionTypeByCustomKey(item.Type);
                 string reference_Answer =  null;
                 if (tempRqType == RealQuestionType.SS || tempRqType == RealQuestionType.MS || tempRqType == RealQuestionType.RW)
                {
                     // 用逗号连接每个正确答案的选项
                     if (item.StandardAnswer !=  null)
                    {
                         if (tempRqType == RealQuestionType.RW)
                        {
                             string standardAnswerValue = item.StandardAnswer[ 0];
                            reference_Answer = standardAnswerValue. Equals( "right", StringComparison.InvariantCultureIgnoreCase) ?  "1" :  "2";
                        }
                         else
                        {
                            reference_Answer =  string. Join( ",",
                                EnglishCharConverter. ConvertEnglishCharArrayToNumberArray(item.StandardAnswer));
                        }
                    }
                }

                 double currentScore = ( double)item.ScoreArray. Sum();
                Question childQuestion =  new  Question();

                 if (knowledgeId !=  null)
                {
                    childQuestion.KnowledgeId = knowledgeId;
                }
                childQuestion.CourseId = courseId;
                 if (custom_Question_Type.HasValue)
                {
                    childQuestion.CustomQuestionType = custom_Question_Type;
                }
                 if (difficultyId.HasValue)
                {
                    childQuestion.Difficulty = difficultyId;
                }
                childQuestion.QuestionType = ( short)tempRqType;
                childQuestion.Score = currentScore;
                childQuestion.QuestionSource =  0;
                childQuestion.IsMachineScore = tempRqType != RealQuestionType.QA ? ( byte) 1 : ( byte) 0;
                childQuestion.ParentId = parentQuestion.Id;
                childQuestion.ScoreRate = currentScore / parentQuestion.Score.Value;
                childQuestion.Status = ( byte)QuestionStatusEnum.UnShared;
                childQuestion.ReferenceId =  0;
                 //DescriptionDir = null,
                childQuestion.CreateDate = DateTime.Now;
                childQuestion.UserId = creator;
                 if (creator_Name !=  null)
                {
                    childQuestion.UserName = creator_Name;
                }
                childQuestion.UseCount =  0;
                childQuestion.CollectCount =  0;
                childQuestion.IsExtract = ( byte)QuestionIsExtractEnum.No;
                childQuestion.IsAnswerable =  1;
                 if (reference_Answer !=  null)
                {
                    childQuestion.ReferenceAnswer = reference_Answer;
                }

                childQuestion.Id = Convert. ToInt32(db. Add(childQuestion));
                 if (childQuestion.Id ==  0)
                {
                     continue;
                }
                 CreateQuestionOptionToDb(db, item, childQuestion, tempRqType);
            }
        }

         /// <summary>
         /// 添加 试题
         /// </summary>
         /// <param name="qmForCp"></param>
         /// <param name="currentQuestion"></param>
         /// <param name="realQuestionType"></param>
         /// <param name="unitOfWork"></param>
         private  void  CreateQuestionOptionToDb(Db db, QuestionModelForClientPost qmForCp, Question currentQuestion, RealQuestionType realQuestionType)
        {
             switch (realQuestionType)
            {
                 case RealQuestionType.SS:
                 case RealQuestionType.MS:
                 case RealQuestionType.RW:
                     CreateSsOrMsOrRwToDb(db, qmForCp, currentQuestion, realQuestionType);
                     break;
                 case RealQuestionType.FB:
                 case RealQuestionType.QA:
                     CreateFbOrQaToDb(db, qmForCp, currentQuestion);
                     break;
                 default:
                     throw  new  NotImplementedException( "未知的题形!");
            }
        }

         /// <summary>
         /// 添加单选 多选 跟判断题
         /// </summary>
         private  void  CreateSsOrMsOrRwToDb(Db db, QuestionModelForClientPost clientQuestionModel, Question currentQuestion, RealQuestionType questionType)
        {
             short i =  0;
             double itemScore = ( double)clientQuestionModel.ScoreArray[ 0];
             foreach ( string questionValue  in clientQuestionModel.QuestionValueArray)
            {
                i++;
                QuestionOption question_Option =  new  QuestionOption()
                {
                    QuestionId = currentQuestion.Id,
                    OptionTitle = questionType == RealQuestionType.RW ? clientQuestionModel.QuestionTitleArray[i -  1] :  string.Empty,  // 目前没有用到,由于题干中已经包含了
                    ReferenceAnswer =  string.Empty,
                     //Score = null,
                    ScoreRate = itemScore / currentQuestion.Score.Value,
                    IsAnswer = clientQuestionModel.StandardAnswer. Contains(questionValue) ? ( byte) 1 : ( byte) 0,
                    OrderNo = ( byte)i
                };
                db. Add(question_Option);
                 //this._question_OptionRepository.DeferInsert(question_Option, unitOfWork);
            }
        }

         /// <summary>
         /// 添加简答题 跟 填空题
         /// </summary>
         /// <param name="db"></param>
         /// <param name="clientQuestionModel"></param>
         /// <param name="currentQuestion"></param>
         private  void  CreateFbOrQaToDb(Db db, QuestionModelForClientPost clientQuestionModel, Question currentQuestion)
        {
             short i =  0;
             foreach ( decimal questionValue  in clientQuestionModel.ScoreArray)
            {
                i++;
                 double itemScore = ( double)questionValue;

                QuestionOption question_Option =  new  QuestionOption()
                {
                    QuestionId = currentQuestion.Id,
                    OptionTitle =  string.Empty,     // 目前没有用到,由于题干中已经包含了
                    ReferenceAnswer = clientQuestionModel.StandardAnswer ==  null ?  "" : clientQuestionModel.StandardAnswer[i -  1],
                    Score = itemScore,
                    ScoreRate = itemScore / currentQuestion.Score.Value,
                    IsAnswer =  0,
                    OrderNo = ( byte)i
                };
                db. Add(question_Option);
                 //this._question_OptionRepository.DeferInsert(question_Option, unitOfWork);
            }
        }

         #endregion

         /// <summary>
         /// 获取试题 选项的模型
         /// </summary>
         /// <param name="questionId"></param>
         /// <param name="questionRenderModel"></param>
         /// <param name="message"></param>
         /// <returns></returns>
         public QuestionViewResult  GetQuestionViewWithQuestionRenderModel( int questionId,  out PaperModelForRender questionRenderModel,  out  string message)
        {
            questionRenderModel =  null;
            message =  null;
            QuestionViewResult qv =  GetQuestionResult(questionId);

             if (qv ==  null || qv.Status == ( short)QuestionStatusEnum.Deleted)
            {
                message =  "您要查看的试题不存在,可能已经被删除了!";
                 return  null;
            }
             if (qv.ParentId !=  0)
            {
                message =  "您要查看的试题是复合题中小题,无法单独查看!";
                 return  null;
            }
            questionRenderModel =  GetSingleQuestionModelForRender(questionId,  1true0);
             return qv;
        }

         /// <summary>
         /// 获取非复合题 的选项
         /// </summary>
         /// <param name="questionId"></param>
         /// <param name="renderQuestionNumber"></param>
         /// <param name="isTakeScoreFromQuestion"></param>
         /// <param name="ifNotTakeThenTotalScore"></param>
         /// <returns></returns>
         public PaperModelForRender  GetSingleQuestionModelForRender( int questionId,  int renderQuestionNumber,  bool isTakeScoreFromQuestion,  double ifNotTakeThenTotalScore)
        {
            QuestionViewResult qview =  GetQuestionResult(questionId);

             if (qview ==  null)
            {
                 return  null;
            }
            RealQuestionType realQuestionType = RealQuestionTypeManager. Convert(qview.QuestionType.Value. ToString());
            IList<QuestionOption> q_options =  null// 非复合题才使用
            IList<QuestionViewResult> childQuestions =  null// 复合题才使用
             if (realQuestionType != RealQuestionType.CP)
            {
                q_options = QuestionOptionBLL. GetQuestionOptionList(questionId);
            }
             else
            {
                childQuestions =  GetChildQuestions(questionId);
            }
            PaperModelForRender resultItem =  new  PaperModelForRender()
            {
                Number = renderQuestionNumber,
                QuestionId = qview.Id,
                QuestionType = realQuestionType,
                TotalScore = isTakeScoreFromQuestion ? qview.Score.Value : ifNotTakeThenTotalScore,
                QuestionDescription = qview.Description,
            };
            List<QuestionChildModelForRender> questionOptions =  new List<QuestionChildModelForRender>();
             switch (realQuestionType)
            {
                 case RealQuestionType.SS:
                 case RealQuestionType.MS:
                 case RealQuestionType.RW:
                    {
                         if (q_options !=  null && q_options.Count >  0)
                        {
                             foreach (QuestionOption q_option_item  in q_options)
                            {
                                 string englishAnswer = EnglishCharConverter. ConvertNumberToEnglishChar(q_option_item.OrderNo). ToString();
                                questionOptions. Add( new  QuestionChildModelForRender()
                                {
                                    Id = q_option_item.Id,
                                    Order_No = q_option_item.OrderNo !=  null ? q_option_item.OrderNo : ( short) 1,
                                    QuestionTitle = realQuestionType == RealQuestionType.RW ? q_option_item.OptionTitle : englishAnswer,
                                    QuestionValue = englishAnswer,
                                    Score = resultItem.TotalScore
                                });
                                 if (q_option_item.IsAnswer ==  1)
                                {
                                     if (! string. IsNullOrEmpty(resultItem.StandardAnswer))
                                    {
                                        resultItem.StandardAnswer +=  ",";
                                    }
                                    resultItem.StandardAnswer += (realQuestionType == RealQuestionType.RW ? q_option_item.OptionTitle : englishAnswer);
                                }
                            }
                        }
                    }
                     break;
                 case RealQuestionType.FB:
                 case RealQuestionType.QA:
                    {
                         if (q_options !=  null && q_options.Count >  0)
                        {
                             foreach (QuestionOption q_option_item  in q_options)
                            {
                                questionOptions. Add( new  QuestionChildModelForRender()
                                {
                                    Id = q_option_item.Id,
                                    Order_No = q_option_item.OrderNo !=  null ? q_option_item.OrderNo : ( short) 1,
                                    QuestionTitle =  null,
                                    QuestionValue =  null,
                                    Score = isTakeScoreFromQuestion ? q_option_item.Score.Value : (resultItem.TotalScore * q_option_item.ScoreRate.Value),
                                    StandardAnswer = q_option_item.ReferenceAnswer
                                });
                            }
                        }
                    }
                     break;
                 case RealQuestionType.CP:
                    {
                         GetCpQuestionInPaper(childQuestions, resultItem, isTakeScoreFromQuestion);
                    }
                     break;
            }
            resultItem.QuestionOptions = questionOptions;
             return resultItem;
        }

         /// <summary>
         /// 获取复合型试题的选项
         /// </summary>
         /// <param name="childQuestions"></param>
         /// <param name="globalResultItem"></param>
         /// <param name="isTakeScoreFromQuestion"></param>
         protected  void  GetCpQuestionInPaper(IList<QuestionViewResult> childQuestions, PaperModelForRender globalResultItem,  bool isTakeScoreFromQuestion)
        {
             if (childQuestions ==  null || childQuestions.Count ==  0)
            {
                 return;
            }
            globalResultItem.ChildQuestionForRenders =  new List<PaperModelForRender>();
             int i =  0;
             foreach (QuestionViewResult childQv_item  in childQuestions)
            {
                i++;

                IList<QuestionOption> child_q_options = QuestionOptionBLL. GetQuestionOptionList(childQv_item.Id);

                RealQuestionType childRealQuestionType = RealQuestionTypeManager. Convert(childQv_item.QuestionType.Value. ToString());
                PaperModelForRender childResultItem =  new  PaperModelForRender()
                {
                    Number = i,
                    QuestionId = childQv_item.Id,
                    QuestionType = childRealQuestionType,
                    TotalScore = isTakeScoreFromQuestion ? childQv_item.Score.Value : (globalResultItem.TotalScore * childQv_item.ScoreRate.Value),
                    QuestionDescription =  null,
                };

                List<QuestionChildModelForRender> questionOptions =  new List<QuestionChildModelForRender>();
                 switch (childRealQuestionType)
                {
                     case RealQuestionType.SS:
                     case RealQuestionType.MS:
                     case RealQuestionType.RW:
                        {
                             if (child_q_options !=  null && child_q_options.Count >  0)
                            {
                                 foreach (QuestionOption child_q_option_item  in child_q_options)
                                {
                                     string englishAnswer = EnglishCharConverter. ConvertNumberToEnglishChar(child_q_option_item.OrderNo). ToString();
                                    questionOptions. Add( new  QuestionChildModelForRender()
                                    {
                                        Id = child_q_option_item.Id,
                                        Order_No = child_q_option_item.OrderNo !=  0 ? child_q_option_item.OrderNo : ( short) 1,
                                        QuestionTitle = childRealQuestionType == RealQuestionType.RW ? child_q_option_item.OptionTitle : englishAnswer,
                                        QuestionValue = englishAnswer,
                                        Score = isTakeScoreFromQuestion ? childQv_item.Score.Value : (childResultItem.TotalScore * child_q_option_item.ScoreRate.Value)
                                    });
                                     if (child_q_option_item.IsAnswer ==  1)
                                    {
                                         if (! string. IsNullOrEmpty(childResultItem.StandardAnswer))
                                        {
                                            childResultItem.StandardAnswer +=  ",";
                                        }
                                        childResultItem.StandardAnswer += englishAnswer;
                                    }
                                }
                            }
                        }
                         break;
                     case RealQuestionType.FB:
                     case RealQuestionType.QA:
                        {
                             if (child_q_options !=  null && child_q_options.Count >  0)
                            {
                                 foreach (QuestionOption child_q_option_item  in child_q_options)
                                {
                                    questionOptions. Add( new  QuestionChildModelForRender()
                                    {
                                        Id = child_q_option_item.Id,
                                        Order_No = child_q_option_item.OrderNo !=  null ? child_q_option_item.OrderNo : ( short) 1,
                                        QuestionTitle =  null,
                                        QuestionValue =  null,
                                        Score = isTakeScoreFromQuestion ?
                                            (child_q_options.Count ==  1 ? childQv_item.Score.Value : child_q_option_item.Score.Value)
                                            :
                                            (childResultItem.TotalScore * child_q_option_item.ScoreRate.Value),
                                        StandardAnswer = child_q_option_item.ReferenceAnswer
                                    });
                                }
                            }
                        }
                         break;
                }
                childResultItem.QuestionOptions = questionOptions;
                globalResultItem.ChildQuestionForRenders. Add(childResultItem);
            }
        }
    }
}

你可能感兴趣的:(orm)