2013-02-10 50 views
0

我有一个tolist方法,使数据库里面的变化,但我想计数多少次我的Where子句是真的。 Tolist的作品如何添加一个计数..mvc3我怎么能包括一个Tolist里面的Count方法

// 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(); 
      } 
+1

看起来像getprofile.count会给你这个答案。但我怀疑,如果这很容易,你不需要发表Q.所以请进一步澄清。 – 2013-02-10 16:55:31

+0

getprofile.count不能用于foreach ..基本上,“articlecount”是数据库中的INT字段,它的唯一目的是保持计算用户创建的文章数量,当您创建新文章Articlecount应该增加+1。我使用.tolist和foreach来更新GetProfile True的所有文章的“articlecount”。 – user1949387 2013-02-10 18:16:08

回答

0

好像你存储在db.Article文章的数量。为什么不存储在db.User中。如果你在db.Article中存储会很困难,因为它必须在每个用户文章中更改Arcticle.articlecount。我认为你上面的代码可能导致不确定性计算。每次在添加文章模式中添加文章时添加文章数。

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(); 

我认为它是安全的。