Inserting datatable data to database using Entity Framework?

c#-4.0 datatable entity-framework

Accepted Answer

A DataTable Entity Framework works with.NET objects, which are fundamentally different from plain rows and columns.

Therefore, it is impossible to simply easily insert the rows and columns from aDataTable EF is used.

It is imperative that you revise yourDataTable Then create objects from those columns and rows, then insert those into aList<YourObject> and then use EF to persist those objects to the database.

You just skip EF and keep the "raw" orDataTable Using raw ADO.NET to the database (SqlDataAdapter or SqlCommand using anINSERT statement).

Update:

You want to convert your OK, soDataTable to things Since you gave me no information, I'm just going to name it a class since you need one to represent your entity in the database.MyObject

public class MyObject
{
   // define some properties
   public int ID { get; set; }
   public string Name { get; set; }
   // whatever else this object has
}

In your database, there most likely already exists an item of this type called a entity class.

Afterward, you must specify a procedure to change the data table into a list of objects:

public List<MyObject> ConvertDataTable(DataTable tbl)
{
     List<MyObject> results = new List<MyObject>();

     // iterate over your data table
     foreach(DataRow row in tbl.Rows)
     {
         MyObject convertedObject = ConvertRowToMyObject(row);
         results.Add(convertedObject);
     }

     return results;
} 

and at this point, you require a final function to change a single row into your object type:

public MyObject ConvertRowToMyObject(DataRow row)
{
     MyObject result = new MyObject();

     // assign the properties of MyObject from the DataRow
     result.ID = row.GetInt32(0);
     result.Name = row.GetString(1);
     // and so on .... convert the column values in the DataRow into the
     // properties of your object type

     return result;
}
3
3/14/2014 12:51:14 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow