uzay95
uzay95

Reputation: 16622

Retrieving one object by using GetTable method over DataContext

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?

Upvotes: 2

Views: 3671

Answers (2)

Nick Craver
Nick Craver

Reputation: 630349

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; }
}

Upvotes: 2

mtmk
mtmk

Reputation: 6316

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.

Upvotes: 0

Related Questions