我正在尝试更新表格中的一行。我找到了一种方法让它工作,但我想知道是否有更简单或更好的方法。请帮助我解决您的任何想法。谢谢
这是代码......
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();
}
答案 0 :(得分:0)
一些想法/观察
您的初始选择集可以缩小为(对不起替代语法)
var list = db.Rubrics.Where(r => r.DepartmentId == 2).Select(x => x.RubricId).ToList()
您对foreach (var rub in courseRubics.ToList())
进行了迭代,但似乎没有对rub
进行任何操作
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]);
}