Tuesday, August 23, 2011

Friday, August 05, 2011

Paging in LINQ

Implementation of paging  with help from ROW_COUNT() of SQL in LINQ :

Implementation:

public static IEnumerable<T> Paging<T>(int rowCount, int pageId, IQueryable<T> query)

{

    return  query       

        .Skip((pageId - 1) * rowCount)

        .Take(rowCount);

}

Using:

private void TestMethod()

{

    Random rnd = new Random();

    List<Foo> fooList = new List<Foo>();

    for (int i = 0; i < 20; i++)

    {

        fooList.Add(

                new Foo

                {

                    ID = rnd.Next(100),

                    Name = Membership.GeneratePassword(5, 0)

                }

            );

    }

 

    var query = fooList.OrderBy(item => item.ID).AsQueryable();

 

   Console.WriteLine("Attempt 1");

   Paging(10, 1,query )

       .ToList()

       .ForEach(

        item => Console.WriteLine(item.ID + ": " + item.Name)

        );

    Console.WriteLine("Attempt 2");

    Paging(5, 2, query)

        .ToList()

        .ForEach(

        item => Console.WriteLine(item.ID + ": " + item.Name)

        );

}

Class:

public class Foo

{

    public int ID { get; set; }

    public string Name { get; set; }

}

 


And now as extension!

Enjoy!

kick it on DotNetKicks.com

Monday, August 01, 2011

Entity Framework and Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

I had troubles with long list in "delete" action. After several unsuccessful attempts I found solution (maybe is not the best):

using (var ctx = new EntityContext())
{
  var tmpTimeout = ctx.CommandTimeout;
  try
  {
   ctx.CommandTimeout = int.MaxValue;
   ctx.YOUROBJECTS.DeleteObject(value));
   ctx.SaveChanges();
  }
  catch (Exception ex)
  {}
  finally
  {
   ctx.CommandTimeout = tmpTimeout;
  }
}