使用LINQtoSQL将记录的计数值插入数据库表

时间:2011-05-04 12:43:53

标签: c# asp.net linq-to-sql record-count

我有一个名为 AllCustomersHistoryOfRecords 的数据库表,该表包含访问我的应用程序/网站的所有用户购买的所有记录的历史记录。还有另一个名为 Components 的表,它只是从我的网站上获取所有可用的组件(用于下载)。现在我想计算 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();

这是我用来将数据插入 Components 表的代码:

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

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

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

我该如何解决这个问题?请帮帮我!!

感谢您的期待

3 个答案:

答案 0 :(得分: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();

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

答案 1 :(得分:1)

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

如果是这种情况,您需要将componentCount转换为可以为null的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();

答案 2 :(得分:1)

您是否尝试在查询中调用.First(),因此结果不会作为IQuerable返回。这篇文章也说明了这一点。

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

相关问题