【问题标题】:mvc3 how can i include a Count method inside a Tolistmvc3 如何在 Tolist 中包含 Count 方法
【发布时间】:2013-02-10 16:36:20
【问题描述】:

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

【问题讨论】:

  • 似乎 getprofile.count 会给你这个答案。但我怀疑如果这么简单,您就不需要发布问题了。所以请进一步澄清。
  • getprofile.count 不适用于 foreach .. 基本上“articlecount”是数据库中的一个 INT 字段,其唯一目的是记录用户创建的文章数量,何时您创建一个新文章 Articlecount 应该增加 +1 。我使用 .tolist 和 foreach 更新使 GetProfile 为 True 的所有文章的“articlecount”。

标签: linq asp.net-mvc-3


【解决方案1】:

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

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

我认为这样更安全。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    相关资源
    最近更新 更多