Reputation: 1343
Using ASP.Net MVC3 with C#
How would I go about selecting a single random record from my database?
This is the code I have now
CJAd cjad = db.CJAds.Single(c => c.category_id == 1 && c.ad_active == true);
Upvotes: 1
Views: 1347
Reputation: 2321
Im on a mobile device so can't check. This should work.
CJAd cjad = db.CJADs.Where(c => c.category_id == 1 && c.ad_active).OrderBy(c => Guid.NewGuid()).FirstOrDefault();
Upvotes: 0
Reputation: 507
var selection = db.CJAds.Where(c => c.category_id == 1 && c.ad_active);
CJAd cjad = selection
.OrderBy(c => c.id)
.Skip(new Random().Next(selection.Count()))
.First();
Upvotes: 3