开发者

Linq to sql convert IQueryable to Dataset

What is the eas开发者_JAVA百科iest way to convert an IQueryable object to a dataset?


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)


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


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜