Fadi Alkadi
Fadi Alkadi

Reputation: 781

How to fill dataset from LINQ

I have created a dataset - how do I fill this dataset with data from a database by a LINQ query? I dont even know if I'm doing right. I want to use this data set as a datasource for my report.

Here's my code:

    public ActionResult Report()
    {
        int OrderId = GetLastOrderId();
      DataClasses1DataContext db = new DataClasses1DataContext();
  var t1 = (from p in db.Varors
                  join
                      op in db.OrderVarors on p.id equals op.IdVara
                  where op.IdOrder == OrderId
                  select new
                  {
                      p.Name,
                      p.details
                  }).ToList();

        MYDATASET ds = new MYDATASET();

       // Somthing LIKE
         ds.add(t1);

            ReportDocument rd = new ReportDocument();
            rd.Load(Path.Combine(Server.MapPath("~/Repport/CrystalReport1.rpt")));
            rd.SetDataSource(t1);

            Response.Buffer = false;
            Response.ClearContent();
            Response.ClearHeaders();


            try
            {
                Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                stream.Seek(0, SeekOrigin.Begin);
                return File(stream, "application/pdf", "EverestList.pdf");
            }
            catch (Exception ex)
            {
                throw;
            }
    }

Upvotes: 0

Views: 2356

Answers (2)

Amit Bisht
Amit Bisht

Reputation: 5136

You Can use this function to convert your list into DataTable and then fill your DataSet with your DataTable

Call it this Way

DataTable dt = new DataTable();
dt = ConvertToDataTable(My_List);  

To Convert to DataTable

public DataTable ConvertToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;
        }

Upvotes: 1

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

You can use DataTableExtensions.CopyToDataTable Method to solve your issue.

For additional information look at this MSDN topics

Creating a DataTable From a Query

Queries in LINQ to DataSet

Upvotes: 2

Related Questions