views:

519

answers:

2

Hi I am currently using TableAdapter that returns a dataTable, which is fine to use when result table should have more than one row like :

MyItemsDataTable myItemsDataTable = Adapter.GetAllItems();  

but if we need only one row as a result, say an item, which has a particular ID

MyItemsDataSet.MyItemRow  itemRow = Adapter.GetItemByID(id)[0];  

how can I make Adapter to return one row instead of DataTable. I am using DataSet Designer wizard and gives me two options for putting in SELECT statement

Use SQL statements -->  Select which return rows
(returns one or many rows)
Use SQL statements -->  Select which returns a single value rows
(returns a single value) 

and using similar query

SELECT * from
FROM  FOOD_ITEMS
WHERE (ITEM_ID = @ITEM_ID)

Do I need to override this method or add a new one ?

public virtual MyItemsDataSet.MyItemsDataTable  GetItemByID(int ITEM_ID)

probably something like

public virtual MyItemsDataSet.MyItemRow GetItemByID(int ITEM_ID)

If so, I cannot do it in designer generated file !! where can I do this ?

Thanks

+1  A: 

I believe the only way is to access the first row in the data table via an index, as you are doing with this query -

MyItemsDataSet.MyItemRow  itemRow = Adapter.GetItemByID(id)[0];  

Another thing you should consider is dumping table adapters and using LINQ2SQL instead. LINQ supports the .FIRST() method, which does precisely what you want.

CraigS
I am already doing this, I need alternative. Some problems with testing.
Asad Butt
+2  A: 

Create a new Select statement in the Dataset Designer. Use Select which return rows. Then use the following query:

SELECT TOP 1 * from 
FROM  FOOD_ITEMS 
WHERE (ITEM_ID = @ITEM_ID)

Save this method as GetFirstItemByID() or something similar.


For the googlers out there, many of the non-MS databases (eg. MySQL) will use the following syntax instead:

SELECT * from 
FROM  FOOD_ITEMS 
WHERE (ITEM_ID = @ITEM_ID)
LIMIT 1
BlueRaja - Danny Pflughoeft
Great, query now returns single row but I still have to fetch it from [0] index of the DataTable. Any way we to add method that returns row instead of DataTable, but using above query ?
Asad Butt
Right-click the dataset file and hit *view code*. It should open `DatasetName.cs` (*NOT* `DatasetName.designer.cs`). Create a new method in the dataset that simply does `return GetFirstItemByID(id)[0];`
BlueRaja - Danny Pflughoeft
Thanks mate, was of great help
Asad Butt