mvc3如何在Tolist中包含Count方法



我有一个tolist方法,可以在数据库中进行更改,但我想计数我的Where子句为true的次数。Tolist工作,我怎么能加一个计数。。

   // the count to see how many times getid== x.RegistrationID 
List<Article> getprofile = (from x in db.Articles where getid == x.RegistrationID select x).ToList();
            foreach (var items in getprofile)
            {
                items.articlecount = items.articlecount + 1;
                db.Entry(items).State = EntityState.Modified;
                db.SaveChanges();
            }

似乎将文章数量存储在数据库中。文章为什么不存储在数据库中。使用者如果存储在数据库中。文章将是困难的,因为它必须在每个用户文章中更改Arcticle.articlecount。我认为您上面的代码可能会导致不确定性计算每次在AddArticle metode中添加文章时添加文章计数。

public void AddArticle(Article article)
    {
        ... your add new article code
        // increase articlecount at db.User
        db.Users.Where(c => c.userid == article.getid).FirstOrDefault().articlecount += 1;
        db.SubmitChanges();
    }

或者不需要存储,只需获取计数:

int articlecount = db.Articles.Where(c => c.getid == RegistrationID ).Count();

我认为这样更安全。

最新更新