Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Im a beginner in LINQ and Entity Framework

Iam using database approach in Entity Framework 6.0 and this c# code for fetching all records with matching date or matching a login name into another DataTable.

var obj = oContext.systevents.Where(r => r.date == Convert.ToDateTime(mdate));

or 

var obj = oContext.systevents.Where(r => r.login == "sara");


Im expecting the output as a set of matching rows into a datatable. My problem is that I am not able to CopyToDataTable Please guide me on this.

Thanks in advance.

What I have tried:

tried like this also..

var obj = oContext.systevents.AsEnumerable().Select(r => r.login == "sara")


Searched... but didn't find a suitable link.
Posted
Updated 11-Jan-19 0:14am
v3
Comments
Maciej Los 11-Jan-19 5:53am    
You should know that DateTime structure returns date and time parts. So, there's minimal chance to get exact match. I think, you should remove time part or create where statement based on date and time between 00:00.00 - 23:59.59.
Priya-Kiko 11-Jan-19 5:59am    
Thanks, I understand, Its not with the date time or any condition, its just iam not able to use the CopyToDataTable extension.

1 solution

Try to use DataTable.LoadDataRow Method (System.Data) | Microsoft Docs[^] together with DataTableExtensions.CopyToDataTable Method (System.Data) | Microsoft Docs[^]. Note: you have to create a desired datatable first!

C#
DataTable destdt = new DataTable();
destdt.Columns.AddRange(new DataColumn[]
    {
        new DataColumn("Field1", typeof(int)),
        new DataColumn("Field2", typeof(string)),
        ...
        new DataColumn("FieldN", typeof(string)),
    });

destdt = oContext.systevents.AsEnumerable()
    .Where(r => r.login == "sara")
    .Select(x => destdt.LoadDataRow(new object[]
    {
        x.Field1, 
        x.Field2,
        ...
        x.FieldN
    }, false)
    .CopyToDataTable();


For further details, please see:
How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow | Microsoft Docs[^]
 
Share this answer
 
Comments
Priya-Kiko 11-Jan-19 6:39am    
Thank you.
Maciej Los 11-Jan-19 6:48am    
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900