0

我有一个 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();
            }
4

1 回答 1

0

seems like you store the number of articles in db.Article. why not stored in db.User. If you store in db.Article will be difficult because it must change Arcticle.articlecount in each user Articles. I think your code above can cause uncertainty calculation. Add article count each time you add article in 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();
    }

or do not need to be stored, to get the count just:

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

I think it's safer.

于 2013-02-10T23:25:45.407 回答