0

我正在尝试更新表中的一行。我找到了一种让它工作的方法,但我想知道是否有更简单或更好的方法。请帮助我解决您可能有的任何想法。谢谢

这是代码……</p>

   var courseRubics = from r in db.Rubrics where r.DepartmentID == 2 select r;
        var selectedRubrics = courseRubics.Select(r => r.RubricID);
        List<int> rubricsList = selectedRubrics.ToList();


        foreach (var rub in courseRubics.ToList())

        {

            if (!String.IsNullOrEmpty(formCollection["item.Weight"]))
            {
                Rubric aRubic1 = db.Rubrics.Find(1);
                Rubric updateRubic1 = (Rubric)aRubic1;
                int rubric1 = Convert.ToInt32(totlrubric[0]);
                updateRubic1.Weight = rubric1;

                Rubric aRubic2 = db.Rubrics.Find(2);
                Rubric updateRubic2 = (Rubric)aRubic2;
                int rubric2 = Convert.ToInt32(totlrubric[1]);
                updateRubic2.Weight = rubric2;

                Rubric aRubic3 = db.Rubrics.Find(4);
                Rubric updateRubic3 = (Rubric)aRubic3;
                int rubric3 = Convert.ToInt32(totlrubric[2]);
                updateRubic3.Weight = rubric3;



            }


            db.SaveChanges();

        }
4

1 回答 1

0

几个想法/观察

  1. 您的初始选择集可以缩小到(对不起替代语法)

    var list = db.Rubrics.Where(r => r.DepartmentId == 2).Select(x => x.RubricId).ToList()
    
  2. 你迭代foreach (var rub in courseRubics.ToList())但似乎没有做任何事情rub

  3. 的内容if...可以收紧一点。我看不出有什么理由需要进行强制转换,或者为什么不能内联 rubricX 的创建,

    if (!String.IsNullOrEmpty(formCollection["item.Weight"]))
        {
            Rubric aRubic1 = db.Rubrics.Find(1);
            aRubic1.Weight = Convert.ToInt32(totlrubric[0]);
    
            Rubric aRubic2 = db.Rubrics.Find(2);
            aRubic2.Weight = Convert.ToInt32(totlrubric[1]);
    
            Rubric aRubic3 = db.Rubrics.Find(4);
            aRubic3.Weight = Convert.ToInt32(totlrubric[2]);
        }
    
于 2013-02-13T01:04:44.907 回答