使用Entity Framework将数据表数据插入数据库?

Mog*_*gli 5 datatable entity-framework c#-4.0

我有一个数据表,我想使用Entity Framework将数据插入数据库(SSMS).什么是可行的解决方案?

mar*_*c_s 5

ADataTable是原始行和列 - 实体框架与 .NET 对象一起工作,这从根本上来说是另一回事。

因此,您不能轻松地使用 EF插入行和列DataTable

要么需要迭代并从DataTable这些行和列中构建对象,将它们粘贴到 a 中List<YourObject>,然后使用 EF 将这些对象持久保存到数据库中。

或者您只需跳过 EF 并使用原始 ADO.NET(或使用语句)将“原始”持久保存DataTable到数据库中。SqlDataAdapterSqlCommandINSERT

更新:

好的,所以你想将你的转换DataTable为对象。您需要有一个类来代表数据库中的实体 - 因为您没有提供任何信息,所以我将调用它MyObject

public class MyObject
{
   // define some properties
   public int ID { get; set; }
   public string Name { get; set; }
   // whatever else this object has
}
Run Code Online (Sandbox Code Playgroud)

您很可能已经在数据库中存在这样一个对象 -实体类。

然后需要定义一个方法将数据表转换为对象列表:

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;
} 
Run Code Online (Sandbox Code Playgroud)

现在您需要最后一个方法将单行转换为对象类型:

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;
}
Run Code Online (Sandbox Code Playgroud)