我想为使用Linq To Sql读取的数据集中的每条记录添加唯一的Id

时间:2014-03-14 16:09:38

标签: c# sql linq

这是我的读物:

    OnSiteV3DataContext _v3Context = new OnSiteV3DataContext();
        var dataset1 = (from sp in _v3Context.SQLPendingEvents
                        where 
                        (sp.EventType.ToString() == str100w)
                        select new
                        {

                            sp.KeyDeviceID,
                            sp.UpdateTime ,
                            sp.EventClass ,
                            sp.EventCode ,
                            sp.EventType ,
                            sp.EventDateTime ,
                            sp.KeyPropertyID,
                            sp.KeyEntityID,
                            sp.EventText,
                            sp.KeyUserID,
                            sp.EventImage,
                            sp.TaskType ,
                            sp.TaskSubType ,
                            sp.UniqueTaskID 
                        }).ToList();

    dataset1 = dataset1.Where(sp => !sp.KeyDeviceID.ToString().Contains('~')).ToList();
        gvSqlPendingEvent.DataSource = dataset1;
        gvSqlPendingEvent.DataBind();

Ther数据集没有唯一标识符来标识单个记录,因此我想添加一个。我希望第一列成为此标识符 - 它可以基于rowcount。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以将查询投影移至客户端并使用Enumerable.Select的重载:

var dataset1 = _v3Context.SQLPendingEvents
                         .Where(sp => sp.EventType.ToString() == str100w)
                         .AsEnumerable() // further processing occurs on client
                         .Select((sp,index) => new {
                             ID = index + 1,
                             sp.KeyDeviceID,
                             sp.UpdateTime ,
                             sp.EventClass ,
                             sp.EventCode ,
                             sp.EventType ,
                             sp.EventDateTime ,
                             sp.KeyPropertyID,
                             sp.KeyEntityID,
                             sp.EventText,
                             sp.KeyUserID,
                             sp.EventImage,
                             sp.TaskType ,
                             sp.TaskSubType ,
                             sp.UniqueTaskID 
                         }).ToList();