views:

565

answers:

4

What is the easiest way to convert an IQueryable object to a dataset?

A: 

The easiest thing to do might be to write an implementation of IDataReader that can wrapper an IEnumerable (IQueryable is an IEnumberable). There is an implementation here. Then you can call DataTable.Load(IDataReader).

Mike Two
+2  A: 

(yourDatacontext).GetCommand(yourIQueryableHere), pass command text to a DbCommand object, call ExecuteReader, pass reader to dataset's .Load method.

nitzmahone
It isn't clear to me that the OP has a DataContext or is talking about a database query. If they are then you're right this is easiest. We just don't know what the IQueryable is.
Mike Two
Except that it's tagged Linq to SQL...
nitzmahone
@nitzmahone - Good point. Gotta learn to read the tags.
Mike Two
+1  A: 

modelshredder has exactly what you need. If you have the datacontext around and don't need the data in terms of your model also, nitzmahone' solution is fine performance wise (if it matches your setup, which is not clear to me)

Johannes Rudolph
A: 

If you create a DataTable from schema so it matches your LINQ to Sql, I have an extension method that takes the IQueryable and fills the DataTable:

public static DataTable AsDataTable(this IQueryable value, DataTable table)
{
    var reader = value.GetEnumerator();

    while (reader.MoveNext())
    {
        var record = (Customer)reader.Current;
        table.Rows.Add(record.CustomerID, record.City);
    }

    return table;
}

Note that the cast to Customer is my TEntity:

[Table(Name = "Customers")]
public class Customer
{
    [Column(IsPrimaryKey = true)]
    public string CustomerID;
    [Column]
    public string City;
}

There are other options that use reflection to build your DataTable from the Customer class. Given the performance hit from reflection, I chose to use the following method to build my table:

public DataTable GetSchema(params string[] columns)
{
    string col_list;

    if (columns.Length == 0)
        col_list = "*";
    else
        col_list = String.Join(", ", columns);

    return Provider.QueryAsDataTable(string.Format("select top 0 {0} from customers", col_list));
}

Putting all that together, I was able to push the results into my DataGridView:

    dgridRO.DataSource = new DataView(rows.AsDataTable(dmap.GetSchema("CustomerID", "City")));


**

ID10TException:

** I spent all this effort getting a conversion from the IQueryable to a DataTable just so I could create a DataView as a source to the DataGridView. Well, I know I didn't need to do that now.

dboarman