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?
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:
Our interface, which is on every class can be very small for this purpose: