2

我有一个名为AllCustomersHistoryOfRecords的数据库表,该表包含访问我的应用程序/网站的所有用户购买的所有记录的历史记录。还有另一个名为“组件”的表,它仅列出了我网站上所有可用(供下载)的组件。现在我想计算AllCustomersHistoryOfRecords中可用的所有记录并更新Components表的字段 *Total_Downloads* 中的计数。这是我正在做的事情:

这主要是计算AllCustomersHistoryOfRecords表中每条记录的出现次数。

var componentCount = from c in db.Components
                                 join cr in db.AllCustomersHistoryOfRecords
                                 on c.Component_Name equals cr.Software_Title into temporary
                                 select temporary.Count();

这是我用来将数据插入到组件表中的代码:

Component comp = new Component { Total_Downloads = componentCount};
db.Components.InsertOnSubmit(comp);

但问题是我收到以下错误:

Cannot implicitly convert type 'System.Linq.IQueryable<int>' to 'int?'

我怎么解决这个问题 ?请帮帮我!!

感谢期待

4

3 回答 3

1

那里不应该有一组括号吗?

var componentCount = (from c in db.Components
                             join cr in db.AllCustomersHistoryOfRecords
                             on c.Component_Name equals cr.Software_Title into temporary
                             select temporary).Count();

编辑:如果我理解正确,你是想得到所有计数的总和吗?如果正确,那么如何:

var componentCount = (from c in db.Components
                             join cr in db.AllCustomersHistoryOfRecords
                             on c.Component_Name equals cr.Software_Title into temporary
                             select temporary.Count()).Sum();

如果没有,那么你能描述一下你想做什么吗?

于 2011-05-04T12:47:52.333 回答
1

我猜 componentCount 字段是一个可为空的字段?

如果是这种情况,您需要将 componentCount 转换为可为空的 int,并从 linq 查询而不是 IQueryable 返回结果集。

    var componentCount = (from c in db.Components
                                     join cr in db.AllCustomersHistoryOfRecords
                                     on c.Component_Name equals cr.Software_Title into temporary
                                     select c).Count();
    Component comp = new Component { Total_Downloads = (int?)componentCount};
    db.Components.InsertOnSubmit(comp);

编辑循环组件和更新计数

您需要将 c.ComponenetId 和 comp.ComponentId 替换为组件表/对象上的主键。可能有一些小问题,因为我没有运行它,但它应该让你很好地了解如何实现你所追求的。

var components = (from c in db.components select c).ToList();
foreach(var comp in components)
{
    var componentCount = (from c in db.Components
                         join cr in db.AllCustomersHistoryOfRecords
                         on c.Component_Name equals cr.Software_Title into temporary
                         where c.ComponentId == comp.ComponentId
                         select c).Count();
    comp.Total_Downloads = (int?)componentCount;                
}
db.SubmitChanges();
于 2011-05-04T12:49:28.587 回答
1

您是否尝试过在查询中调用 .First() 以使结果不会作为 IQuerable 返回。这在这篇文章中也有说明。

无法将类型“System.Linq.IQueryable”隐式转换为“int?”

于 2011-05-04T13:23:38.627 回答