使用Entity Framework将数据类型数据插入数据库? [英] Inserting datatable data to database using Entity Framework?

查看:226
本文介绍了使用Entity Framework将数据类型数据插入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having a datatable and i want to insert data to database(SSMS) using Entity Framework. What is the Feasible solution for this ?

推荐答案

A DataTable 行和列 - Entity Framework使用.NET对象,这基本上是其他东西。

A DataTable is raw rows and columns - Entity Framework works with .NET objects, which is fundamentally something else.

所以你不能只是轻松插入行和列从 DataTable 使用EF。

So you cannot just easily insert the rows and columns from a DataTable using EF.

需要遍历 DataTable 并从这些行构建对象&列,将它们粘贴到 List< YourObject> 中,然后使用EF将这些对象保存到数据库....

You either need to iterate through your DataTable and build up objects from those rows & columns, stick those into a List<YourObject> and then persist those objects to the database using EF....

,您只需跳过EF并使用原始ADO.NET( SqlDataAdapter)将原始 DataTable SqlCommand INSERT 语句)。

or you just skip EF and persist the "raw" DataTable to the database using raw ADO.NET (SqlDataAdapter or SqlCommand with an INSERT statement).

更新:

确定,因此您要转换 DataTable 到对象。你需要一个类来表示你的实体在数据库中 - 因为你没有提供任何信息,我只是打电话 MyObject

OK, so you want to convert your DataTable to objects. You need to have a class that represents your entity in the database - since you provided no information, I'm just going to call it MyObject

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

有一个实体类存在于您的数据库中。

You most likely already have such an object - an entity class - that exists in your database.

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

Then you need to define a method to convert the data table to 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 now you need a last method to convert a single row to 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;
}

这篇关于使用Entity Framework将数据类型数据插入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆