0

Here is my action code

public class personnelViewModel{
    public Guid PKPersonelID { get; set; }
    public string name { get; set; }
    public string family { get; set; }
    public int usageCount { get; set; }
}

var model = from personnel in DB.RFH_Personnel select new personnelViewModel 
                                                        { 
                                                            PKPersonelID = personnel.PKPersonelID,
                                                            name = personnel.Name,
                                                            family = personel.Family 
                                                        }
freach(var item in model)
    item.usageCount = DB.RFH_Service.Count(d => d.FKPersonelID == item.PKPersonelID);

return View(model);

and this is my view:

@model IEnumerable<RefahiWeb.Models.personnelViewModel>
@{    
    var grid = new WebGrid(source: Model, rowsPerPage: 15, canPage: true, canSort: true);
}

@grid.GetHtml(tableStyle: "table tablesorter table-bordered table-hover request-status",                    
                mode: WebGridPagerModes.All,
                columns: grid.Columns(
                        grid.Column("name", "name", canSort: false),                         
                        grid.Column("family", "family", canSort: false),     
                        grid.Column("usageCount", "usageCount", canSort: false)
                )
        )

the problem is that usageCount is always set to zero and the value that is set in froeach loop does not change the value of usageCount. Any help is appreciated in advance.

4

1 回答 1

0

你的问题是你没有注意到这model 只是一个查询。当您遍历 . 时model,更改所有内容,但返回时,您只需重新执行.存储的查询model。因此,要解决此问题,您至少有 2 个选择:

  • ToList()在之后附加model,然后一切都应该工作:

    var model = from personnel in DB.RFH_Personnel 
                select new personnelViewModel  { 
                                                PKPersonelID = personnel.PKPersonelID,
                                                name = personnel.Name,
                                                family = personel.Family 
                                               }.ToList();
    
  • 在查询中分配usageCount权限,如下所示:

    var model = from personnel in DB.RFH_Personnel 
                select new personnelViewModel  { 
                                                PKPersonelID = personnel.PKPersonelID,
                                                name = personnel.Name,
                                                family = personel.Family, 
                                                usageCount = DB.RFH_Service.Count(d => d.FKPersonelID == personnel.PKPersonelID)
                                               };
    

注意:我不知道你的View方法接受什么,但是当你附加ToList()你的模型时List...,你应该考虑到这一点来相应地修改你的代码。

于 2013-10-20T14:16:21.117 回答