orderby newid()

Posts   
 
    
jspuij
User
Posts: 24
Joined: 22-Jan-2007
# Posted on: 16-Sep-2009 18:22:04   

Is there a way to write

orderby newid()

easily with linq? Combined with top 1 this gets a random record from the database.

I tried creating a function mapping, but it seems that Linq to LLBLGen Pro doesn't emit it in the query, unless the function has an argument that e.g. contains one of the fields.

jspuij
User
Posts: 24
Joined: 22-Jan-2007
# Posted on: 16-Sep-2009 18:31:32   

btw, used crappy hack now:

create view [dbo].[randomguid]
as
    select newid() as id
GO



CREATE FUNCTION [dbo].[fn_NewID]
(
    @ID uniqueidentifier
)
RETURNS uniqueidentifier
AS
BEGIN
    return (select id from randomguid)
END


GO

and then map a .NET function to this sql one, including id that is never used.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 17-Sep-2009 05:33:24   
David Elizondo | LLBLGen Support Team
jspuij
User
Posts: 24
Joined: 22-Jan-2007
# Posted on: 17-Sep-2009 09:33:02   

Already got a workaround with linq. Would be nice though if a functionmapping without arguments or even a default function mapping would be available.

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 17-Sep-2009 11:34:07   

Already got a workaround with linq

Could you please share it.

jspuij
User
Posts: 24
Joined: 22-Jan-2007
# Posted on: 28-Sep-2009 17:33:19   

see SQL script above and then:


                LinqMetaData metaData = new LinqMetaData();

                metaData.CustomFunctionMappings = new FunctionMappingStore();
                metaData.CustomFunctionMappings.Add(new FunctionMapping(typeof(GuidExtensions),"Random",1,"dbo.fn_newID({0})"));

                var result = ( from t in metaData.Tips
                                     orderby GuidExtensions.Random(t.TipId)
                                     select t).FirstOrDefault();

and for guidextensions.cs


public static class GuidExtensions
    {
        public static Guid Random(Guid id)
        {
            throw new NotImplementedException();
        }
    }

Posts: 13
Joined: 01-Mar-2012
# Posted on: 01-Mar-2012 15:09:35   

try it like this:

metaData.CustomFunctionMappings.Add(new FunctionMapping(typeof(GuidExtensions),"Random",1,"NewID(), {0}"));

and you don't have to create the view and the scalar function