mapping datatable columns mapper class

Dondapati, Navin 281 Reputation points
2022-01-21T18:08:49.77+00:00

I have a psv file, i read data from the file and put it in to C# datatable.
Now i have to insert data in to sql table. The header names are different in my datatable and sql table.
I have a mapper class to map the columns. How do i connect mapper class to datatable?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
323 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,306 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 26,146 Reputation points
    2022-01-21T18:45:01.377+00:00

    I have a mapper class to map the columns. How do i connect mapper class to datatable?

    The community can only evaluate code that is shared on the forum. We have no idea how the mapper class works or how the data access is implemented.

    LINQ can query a DataTable and return any type of object you like. The following link shows how that works.

    Single-Table Queries (LINQ to DataSet)

    0 comments No comments

  2. Dondapati, Navin 281 Reputation points
    2022-01-21T18:55:01.79+00:00

    using (var csvReader = new TextFieldParser(file))
    {

               csvReader.SetDelimiters(new string[] { "|" });
                csvReader.HasFieldsEnclosedInQuotes = true;
                string[] colFields = csvReader.ReadFields();
                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    dt.Columns.Add(datecolumn);
                }
    
                while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();
                    //Making empty value as null
                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    dt.Rows.Add(fieldData);
                }
    

    public VCClassMap()
    {

            Map(m => m.C_ID).Name("CID");
            //Map(m => m.A_ID).Name("AId");
            Map(m => m.G_ID).Name("GId");
    

    }

    I need to check each column in DT and rename with corresponding id of the mapper class.