views:

40

answers:

3

I'm doing the following:

public MyItem FetchSingleItem(int id)
{
  string query = "SELECT Something FROM Somewhere WHERE MyField = {0}";
  IEnumerable<MyItem> collection = this.ExecuteQuery<MyItem>(query, id);
  List<MyItem> list = collection.ToList<MyItem>();
  return list.Last<MyItem>();
}

It's not very elegant really and I was hoping there's something a little better to get a single item out using DataContext. I'm extending from DataContext in my repository. There's a valid reason why before you ask, but that's not the point in this question ;)

So, any better ways of doing this?

Cheers

A: 

If it is SQL Server, change your SQL to:

SELECT TOP 1 Something FROM Somewhere ...

Or alternatavely, change these lines

List<MyItem> list = collection.ToList<MyItem>();
return list.Last<MyItem>();

into this one:

return collection.First();
Konamiman
A: 
myDataContext.MyItem.Where(item => item.MyField == id)
    .Select(item => item.Something)
    .FirstOrDefault();
Matt
Should be First(), I think, as his existing code throws when the list is empty.
Craig Stuntz
I tought of this too, but assumed that he was using direct SQL for some good reason.
Konamiman
I mean that List<T>.Last() will throw. The SQL won't, I agree.
Craig Stuntz
I need it in regular SQL unfortunately. Requirement, not my choice, if I had the choice I'd do it in LINQ2SQL.
Kezzer
@Kezzer. Ahh, bummer. I'll leave this up cause elsewise you're likely to get another similar answer.
Matt
A: 

The record returned is undefined, since you have no ORDER BY. So it's hard to do an exact translation. In general, though, reverse the order and take the First():

var q = from s in this.Somewhere
        where s.MyField == id
        orderby s.Something desc
        select s.Something;
return q.First();

Relational tables are unordered. So if you don't specify the record you want precisely, you must consider the returned record as randomly selected.

Craig Stuntz