2013-02-10 84 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(); 

我認爲它是安全的。