Linq to sql convert IQueryable to Dataset

前端 未结 4 484
谎友^
谎友^ 2021-01-06 11:48

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

相关标签:
4条回答
  • 2021-01-06 12:06

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

    0 讨论(0)
  • 2021-01-06 12:11

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

    0 讨论(0)
  • 2021-01-06 12:11

    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 讨论(0)
  • 2021-01-06 12:15

    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)

    0 讨论(0)
提交回复
热议问题