简体   繁体   中英

Insert JSON record into SQL Server database

I have an open SqlConnection (extended by Dapper), a table name in the connected database, and a JSON string that I trust to be of the same schema. What's the simplest way to insert the JSON object's field values without deserializing to a static type?

I realize the standard option is to create a class representing the record to deserialize into. However, there are several reasons this is less than ideal. I'm syncing a number of tables in exactly the same way. The schema already exists in two places (the source and the target), so it seems poor form to repeat the schema in the middleware as well. Also, since I'm just going straight into the database, it seems excessive to require a recompile any time someone adds an additional column or table.

Is there a more dynamic solution?

probably deserializing into a dynamic is your best bet. if you want to pull out the values directly from the string, you're going to have to (at least partially) parse it anyways, and at that point you might as well just deserialize it

See this answer for an example using JSON.net: Deserialize json object into dynamic object using Json.net

Deserialize into a dictionary, then construct Dapper DynamicParameters.

How to create arguments for a Dapper query dynamically

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