Search code examples
c#sql-serverstrongly-typed-dataset

Getting one row from a Strongly Typed dataset without getting who table


I currently have this code:

   /// <summary>
    /// This is an ineffecient method of getting a tenant by their id.
    /// </summary>
    /// <param name="id">int ID of the tenant to be selected</param>
    /// <returns>Tenant with the specific ID, or null if not found.</returns>
    public static Tenant GetTenantByID(int id){
        RentalEaseDataSetTableAdapters.tblTenantTableAdapter adapter = new RentalEaseLogic.Database.RentalEaseDataSetTableAdapters.tblTenantTableAdapter();
        RentalEaseDataSet ds = new RentalEaseDataSet();

        adapter.Fill(ds.tblTenant);

        DataRow[] rows = ds.tblTenant.Select("ID = " + id);

        if (rows.Length > 0) {
            return new Tenant(rows[0] as RentalEaseDataSet.tblTenantRow);
        } else {
            return null;
        }
    }

Which is pretty terrible in performance. It grabs and loads a large table everytime someone wants one row. There has to be a better way.

How can I select one row from a table, without having to fill an entire table and still keep the strong data typing?


Solution

  • There is. Associate a query with your TableAdapter. TableAdapter Overview and mainly How to: Create TableAdapter Queries.

    Then you fill the dataset with the queried rows.