tags:

views:

38

answers:

2

I have a class is inherited from DataContext to use Linq.

public class Context : DataContext
{
    public Context(string connectionString)
        : base(connectionString)
    {
    }
}


[Table(Name = "TableNameee")]
public class ClassOfTable
{

}

And i have another class which is mapped to a table. I am using

context.GetTable<ClassOfTable>()

method to retrieve all rows of table which is mapped to ClassOfTable class. But i want to retrieve just one row from the table of the database. I can use it like this:

ClassOfTable cls = context.GetTable<ClassOfTable>().Where(p=>p.id==1).First();

But this will retrieve every rows of table. And i don't want to do this. What should i do to take only one row from table?

+1  A: 

It won't get all the rows of a table, it will just get the 1 row via a where statement in the SQL. Remember that Linq is a deffered execution model, GetTable<T> does't actually run anything, only when .First() runs is anything called.

We add this method to our DataContext to do just this often, here it's in extension form:

public static T GetById<T>(this DataContext dc, long id) where T : class, IBaseEntity
{
  return dc.GetTable<T>().Single(t => t.Id == id);
}

Our interface, which is on every class can be very small for this purpose:

public interface IBaseEntity
{
    long Id { get; set; }
}
Nick Craver
Thank you for your answer. I will test it tomorrow. Thank you very much again.
uzay95
Hi Nick. I wonder that how did you extend Context class while it is not static (as you know, if we want to extend Context class from DataContext class, we can't set it as a static class can we?)
uzay95
@uzay95 - Usually when you generate the DataContext class it's a partial, so just stick the method in another partial `.cs` of the same class type: http://msdn.microsoft.com/en-us/library/wa80x488(VS.80).aspx Alternatively...just use the extension method above in a static class and it'll show up in intellisense: http://msdn.microsoft.com/en-us/library/bb383977.aspx
Nick Craver
Absoultly you are right. And thank you for the links.
uzay95
A: 

No it wouldn't. I know it looks like it will, but linq2sql actually works out the necessary 'most' efficient SQL. You can try it and check the issued queries using the profiler.

Maxwell Troy Milton King
You can use http://www.linqpad.net/ to easily see what SQL your queries generate.
Dan Diplo
Good one. Didn't know that. Thanks Dan.
Maxwell Troy Milton King