简体   繁体   中英

Inserting a datatable into SQL Server

I currently have a populated datatable, but I'm having trouble inserting it into my existing (empty) database.

I have looked into sqlbulkcopy as well, but haven't had much luck.

Although using Entity Framework I would expect:

_db.TableName.AddRange(dt);

To properly insert the new data from my datatable.

Where am I going wrong here?

You are missing a few steps. First you need to create the table on the database, this is generally done not at run time for lots of complex reasons. Research Entity Framework Code First for more details on how to do this.

Secondly if you truly want to use Entity Framework you will need to convert your data table into a set of objects of the correct type.

Honestly though I would avoid Entity Framework and embed a CREATE TABLE script (or even better define it before you execute) and then use SqlBulkCopy, just note that SqlBulkCopy needs the table defined ahead of time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM