【问题标题】:get count from Iqueryable<T> in linq-to-sql?从 linq-to-sql 中的 Iqueryable<T> 获取计数?
【发布时间】:2011-02-15 10:16:15
【问题描述】:

以下代码似乎没有得到正确的计数.....

 var materials = consRepository.FindAllMaterials().AsQueryable();
 int count = materials.Count();

这是这样做的方式吗....这是我获取记录的存储库...

public IQueryable<MaterialsObj> FindAllMaterials()
        {
           var materials =  from m in db.Materials
            join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id
                   where m.Is_Deleted == 0
                   select new MaterialsObj()
                   {
                       Id = Convert.ToInt64(m.Mat_id),
                       Mat_Name = m.Mat_Name,
                       Mes_Name = Mt.Name,
                   };
            return materials;

        }

编辑:

当我使用这个时,

        var materials = consRepository.FindAllMaterials().AsQueryable();
        return View("Materials", materials);

我的表中有 18 行...所以我不能将计数设为18,而是给出12

回答:

Breakpoint 似乎没有产生结果,但 response.Write(count) 产生了结果...

【问题讨论】:

  • 你为什么要转换成IQueryableIQueryable&lt;MaterialsObj&gt; 已经有一个 Count() 方法。您观察到预期计数和实际计数之间有什么差异?
  • 你怎么知道计数不正确?它应该返回什么而不是返回什么?
  • 这不行,重新安装Windows。

标签: asp.net-mvc linq-to-sql count iqueryable


【解决方案1】:

这应该得到正确的计数:

int count = consRepository.FindAllMaterials().Count();

您如何在视图中迭代模型?

您是否有可能显示重复的条目?

【讨论】:

    【解决方案2】:

    是否有可能您没有加入正确的列?我问的唯一原因是您的 id 列在每个类中的命名不一致。对于材质,您使用的是Mat_id,但在MeasurementTypes 中您使用的是Id。这让我想知道您是否正在尝试将自然键值与人工主键而不是相应的自然外键连接起来。

    【讨论】:

    • @tvanoffosson db.MaterialsmeasurementTypeId 这是一个外键,它的主键表是db.MeasurementTypes,主键字段是Id...
    • @Pandiya - 代码看起来应该对我有用,所以我认为查询一定有问题。这是我看到的唯一可能是问题的东西。
    猜你喜欢
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多