使用C#中的foreach将记录从表移动到另一个表

时间:2018-02-09 18:49:24

标签: c# database linq foreach

我的代码

        tbl_Birthday tblB = new tbl_Birthday();
        string today = "01/10/2018";
        var query = from a in db.tbl_users.ToList() where a.birthday == today select a;
        if (query.Count() > 0)
        {
            foreach (var a in query.ToList())
            {
                tblB.name = a.name;
                tblB.score = a.core;
            }
            db.tbl_Birthdays.InsertOnSubmit(tblB);
            db.SubmitChanges();
        }
        dataGridView1.DataSource = from a in db.tbl_Birthdays select a;

这只返回一条记录到我的DataGridView中,但是我有一条记录符合这个条件

1 个答案:

答案 0 :(得分:2)

您需要在InsertOnSubmit循环内移动foreach。目前,您的foreach循环只是一遍又一遍地设置namescore属性,直到退出为止。然后在单个项目上调用SubmitChanges

foreach (var user in db.tbl_users.Where(user => user.birthday == "01/10/2018"))
{
    db.tbl_Birthdays.InsertOnSubmit(
        new tbl_Birthday{ name = user.name, score = user.score });
}

db.SubmitChanges();