无法使用linq更新

时间:2014-04-14 04:57:53

标签: c# .net linq

我编写了以下代码来更新表格的VoterStatus

var vtrs = (from k in db.Voters
            where k.VoterID.Equals(vid)
            select k);
if (vtrs != null)
{
    foreach (Voters vx in vtrs)
    {
        vx.VoterID = vid;
        vx.VoterStatus = 3;
    }
    db.Voters.InsertOnSubmit(voter);
    db.SubmitChanges();
}

此处VoterID是Voters表的主键。它正在提高SqlException

  

无法在dbo.Voters中的VoterID中插入null

我也试过

var vtrs = (from k in db.Voters
            where k.VoterID.Equals(vid)
            select k);
if (vtrs != null)
{
    foreach (Voters vx in vtrs)
    {
        vx.VoterStatus = 3;
    }
    db.Voters.InsertOnSubmit(voter);
    db.SubmitChanges();
}

4 个答案:

答案 0 :(得分:1)

var vtrs = (from k in db.Voters
            where k.VoterID.Equals(vid)
            select k);
    if (vtrs != null)
    {
        foreach (Voters vx in vtrs)
        {

            vx.VoterStatus = 3;
        }
        db.SubmitChanges();
    }

答案 1 :(得分:1)

var vtrs = (from k in db.Voters
                       where k.VoterID.Equals(vid)
                       select k);
        if (vtrs != null)
        {
            foreach (Voters vx in vtrs)
            {
                vx.VoterID = vid;
                vx.VoterStatus = 3;
            }
            db.Voters.InsertOnSubmit(voter);
            db.SubmitChanges();

在您的代码中什么是选民,它不会在任何地方声明。试试这个

var vtrs = (from k in db.Voters
                       where k.VoterID.Equals(vid)
                       select k);
        if (vtrs != null)
        {
            foreach (Voters vx in vtrs)
            {

                vx.VoterStatus = 3;
                //db.Voters.InsertOnSubmit(vx); Only use this when inserting
            }

            db.SubmitChanges();

答案 2 :(得分:1)

这是你的错误:

var vtrs = (from k in db.Voters
                           where k.VoterID.Equals(vid)
                           select k);
            if (vtrs != null)
            {
                foreach (Voters vx in vtrs)
                {

                    vx.VoterStatus = 3;
                }
                db.Voters.InsertOnSubmit(voter); // what is voter pass here vx
                db.SubmitChanges();
            }
像这样:

var vtrs = (from k in db.Voters
                               where k.VoterID.Equals(vid)
                               select k);
                if (vtrs != null)
                {
                    foreach (Voters vx in vtrs)
                    {

                        vx.VoterStatus = 3;
                    }
                    db.Voters.InsertOnSubmit(vx);
                    db.SubmitChanges();
                }

答案 3 :(得分:1)

请您删除以下行,更新实体不需要,

db.Voters.InsertOnSubmit(voter);// also here is one typo , check your entity object name

more info