Search code examples
linqdatatablewebmethod

CopyToDataTable in LINQ


With the reference of this i add a methods in WebForm1.aspx.cs

Reference link

but when i add and build my code then there is error

Extension method must be defined in a top level static class; CustomLINQtoDataSetMethods is a nested class

Extension method must be defined in a top level static class; CustomLINQtoDataSetMethods is a nested class

I do this because i have web method

[WebMethod]
    public static DataTable search_data(DateTime fromdate, DateTime todate, string regiondrop)
    {

        try
        {

            T1 ts = new T1();
            var dq = (from vv in ts.tblVe
                      join rv in ts.tblReg on vv.ID equals rv.ID
                      join re in ts.tblRegi on rv.RID equals re.RID
                      where
                      re.Region == regiondrop
                      && re.StartDate <= fromdate
                      && re.EndDate >= todate
                      orderby
                      vv.ID,
                      rv.OwnerName
                      select new
                      {
                          ID = vv.ID,
                          ownername = rv.OwnerName,
                          RegNo = rv.RegNo,
                          Speed = rv.Speed,
                      });
            var dt = dq.cop();
                     }
        catch (Exception)
        {
            throw new Exception();

        }

    }

when i add this line var dt = dq.cop(); with the reference and answer of this question reference 2 then CopyToDataTable is not in intellisence list

In dq the data is

[0] = { ID = 1, OName = "Khn", RegNo = "AJ-24",Speed = "124" }
[1] = { ID = 2, OName = "hah", RegNo = "AL-91",Speed = "95" }

Solution

  • It tells exactly what the problem is. You have to define extention methods in a public not-nested class. As mentioned on MSDN:

    public static class CustomLINQtoDataSetMethods
    {
        public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
        {
            return new ObjectShredder<T>().Shred(source, null, null);
        }
    
        public static DataTable CopyToDataTable<T>(this IEnumerable<T> source,
                                                    DataTable table, LoadOption? options)
        {
            return new ObjectShredder<T>().Shred(source, table, options);
        }    
    }
    

    And you've most likely put the CustomLINQtoDataSetMethods inside other class. Make sure it's outside of any other classes and the issue should be fixed.