使用LINQ更新表

时间:2011-07-11 23:49:04

标签: c# linq linq-to-sql linqpad

有人可以告诉我为什么下面的代码没有更新LINQPad中的StudentID吗?

var studentsList = Students.Select(t => t);

int newStudentID = 10001;
foreach(Student s in studentsList)
{      
   s.StudentID = newStudentID;            
   newStudentID = newStudentID + 1;   
}

SubmitChanges();

谢谢!

1 个答案:

答案 0 :(得分:0)

不确定;我试着编写代码来测试这个使用你给的代码片段但是可以在LinqPad下编译;这是我用过的东西:

public class Student
{
    public string name; 
    public int StudentId; 
}

void Main()
{
    Student[] Students = 
    new Student[] 
        { 
            new Student { name="a", StudentId = 0}, 
            new Student { name="b", StudentId = 0}, 
            new Student { name="c", StudentId = 0}, 
            new Student { name="d", StudentId = 0}
        };

    var studentsList = Students.Select(t => t);

    int newStudentID = 10001;
    foreach(var s in studentsList)
    {      
       s.StudentId = newStudentID;            
       newStudentID = newStudentID + 1;   
    }

    foreach(var s in studentsList)
    {      
       System.Console.WriteLine(s.name + ": " + s.StudentId.ToString());
    }
}

这是输出:

a: 10001
b: 10002
c: 10003
d: 10004

所以看起来好多了。如果你能提供足够的上下文来获得代码的运行示例,我很乐意进一步检查它。