Page 1 of 1

Linq random rows

Posted: Wed 03 Jul 2013 20:36
by ymorales
Hi.
I want do that:

Code: Select all

var products = db.Styles.OrderBy(e => Guid.NewGuid()).ToList();
With Visual Studio 2012 ado.net entity data model I can do that and no error. But with you LinqConnect model I cant, give me an error.

"Error on executing DbCommand."
InnerException: "The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name."

I must get data from sql from this way:

Code: Select all

SELECT * FROM styles ORDER BY NEWID()
I dont want to use Ado.Net entity model and SQL command.
I bought you component and I like it. There is any way to do that in LinqConnect model?
Thanks

PS: My goal is get rows randomly, Im using Microsoft Sql Server

Re: Linq random rows

Posted: Thu 04 Jul 2013 11:03
by MariiaI
ymorales wrote: There is any way to do that in LinqConnect model?
Please try re-writing your query in the following way and notify us about the results:

Code: Select all

var products = db.Styles
                    .ToList()
                    .Select(e => new { results = e, Guid = Guid.NewGuid()})
                    .OrderBy(e => e.Guid)
                    .Select(e => e.results)
                    .ToList();

Re: Linq random rows

Posted: Fri 05 Jul 2013 13:44
by ymorales
Nice thanks. I dont know why typing ToList() before the orderby it solve the problem.

Solution:
var products = db.Styles.ToList().OrderBy(e => Guid.NewGuid()).ToList();

Re: Linq random rows

Posted: Mon 08 Jul 2013 09:19
by MariiaI
The .ToList() method forces the execution of the query and enumerates all resulting objects to the list of results. After this OrderBy is performed on the client side via LINQ to Objects (OrderBy(e => Guid.NewGuid())).