Jeremy Sullivan
Jeremy Sullivan

Reputation: 1005

Adding a random Guid column to a Linq to Entities query to grab random records

I've found some articles about using the RandomView view and the GetNewID function to pull back randomized records, but they are using this method with Linq to SQL which allows Functions and Stored Procs to be used with no return value or a scalar return value. From what I understand, a Stored Proc has to been returned as one of the Entity Framework objects from my generated model. I have been able to get that to work as an object, but not returning a scalar or no return set.

What I want to do is to simply add a column to my Linq query that contains a newly generated Guid so that I can order by the new Guids and take a specific number of records randomly. Can anyone help with some sort of lambda expression or join that would enable me to do this? It seems like it should be something built into EF, but I understand that we are on EF v1.

(Please provide code in VB.net)

Upvotes: 2

Views: 2069

Answers (2)

Robert Harvey
Robert Harvey

Reputation: 180858

In the Select clause of your Linq query, you should be able to insert a GUID like this:

var result = from myRecord in myTable
    select new {
        field1 = myRecord.field1,
        field2 = myRecord.field2,
        guidField = Guid.NewGuid()
    };

Upvotes: 3

Robert Harvey
Robert Harvey

Reputation: 180858

Well, my VB is a little rusty, but I think this will work...

Dim result = 
    From myRecord in myTable _   
    Select field1, _
           field2,  _
           guidField = System.Guid.NewGuid()

Upvotes: 2

Related Questions