更新数据库中的行

时间:2013-05-12 13:11:31

标签: c# sql ado.net

我正在使用c#和ADO .NET实体数据模型开发应用程序。我有一个表文章(idArticle,nameArticle,statusArticles)。我想检索statusArticle = false的第一篇文章,并将她的值更新为true。有人可以帮我解决这个问题:

   private void button_Click(object sender, EventArgs e)
        {
            using (DbEntities db = new DbEntities())
            {
               Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
                if (firstArticle != null)
                {
                    firstArticle.statusArticle = true;
                    MessageBox.Show("Article validated", "OK");
                    this.Refresh();
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

.FirstOrDefault()

public static TSource FirstOrDefault<TSource>(
    this IEnumerable<TSource> source //db.Articles
)

将返回:

  

默认(TSource),如果source为空;否则,源中的第一个元素。

默认(TSource)为引用类型元素返回null或为值类型元素返回(通常)0

您修改的代码:

 private void button_Click(object sender, EventArgs e)
        {
            using (DbEntities db = new DbEntities())
            {
               Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
                if (firstArticle != null)
                {
                    firstArticle.statusArticle = true;
                    MessageBox.Show("Article validated", "OK");
                    db.SaveChanges(); //change (can go before/after validation message)
                    this.Refresh();

                }
            }
        }

答案 1 :(得分:1)

这可以按照以下方式完成

    private void button_Click(object sender, EventArgs e)
    {
        using (DbEntities db = new DbEntities())
        {
           Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
           // firstArticle is not null anyways as you are calling FirstOrDefault()
         **EDIT** // In case nothing has status = false, you will get a new Articles object, so instead of the below null check, you have to check for other property like id or name that will be unique.
            if (firstArticle != null)
            {
                firstArticle.statusArticle = true;
                db.SaveChanges();
                MessageBox.Show("Article validated", "OK");
                this.Refresh();
            }
        }
    }