简体   繁体   English

如何使用C#将字典保存到数据库中?

[英]How to save a dictionary into a database with C#?

I have been using following way to save dictionaries into the database: 我一直在使用以下方式将字典保存到数据库中:

  1. Convert the dictionary to XML. 将字典转换为XML。
  2. Pass this XML to a SP(Stored Procedure). 将此XML传递给SP(存储过程)。
  3. In the SP use: 在SP中使用:

     Select Key1, Value1 into #TempTable FROM OPENXML(@handle, '//ValueSet/Values', 1) WITH ( key1 VARCHAR(MAX), value1 varchar(100) ) 
  4. Done. 完成。

Is there a way to save dictionaries to a database without converting it to XML? 有没有办法将字典保存到数据库而不将其转换为XML?

Serialize the Dictionary, and store the binary data. Serialize Dictionary,并存储二进制数据。

Then De-Serialize your data back into Dictionary . 然后将数据反序列化为Dictionary

Tutorial1 Tutorial2 Tutorial1 Tutorial2

It depends whether... 这取决于是否......

  • You want the data to be stored: The fastest way (both implementation and performance) to do that is by binary serialization ( Protocol buffers for example). 您希望存储数据:执行此操作的最快方式(实现和性能)是通过二进制序列化(例如协议缓冲区 )。 However the data is not readable with a select and every application who needs to read the data must use the same serialization (if it exists in the same technology/language). 但是,select不能读取数据,每个需要读取数据的应用程序必须使用相同的序列化(如果它存在于相同的技术/语言中)。 From my point of view, it breaks the purpose of storing in a SQL database . 从我的角度来看,它打破了存储在SQL数据库中目的

  • You want the data to be readable by humans: XML is an option while not so fast and a little bit difficult to read and still it is not query-able. 您希望人类可以读取数据: XML是一种选择,而不是那么快,有点难以阅读,但仍然无法查询。 However, it is quite fast to implement. 但是,实施起来非常快。 You can also dump the result to a file and it's still readable. 您也可以将结果转储到文件中,它仍然可读。 Moreover, you can share the data with other applications as XML is a widespread format. 此外,您可以与其他应用程序共享数据,因为XML是一种广泛使用的格式。

  • You want the data to be query-able. 您希望数据可查询。 Depending on the way you go, it could be not so easy to implement. 根据您的方式,实施起来可能并不容易。 You would need two tables (one for keys and one for values). 您需要两个表(一个用于键,一个用于值)。 Then you could write either your own custom mapping code to map columns to properties or you could use frameworks for mapping objects to tables like Entity framework or NHibernate . 然后你可以编写自己的自定义映射代码来将列映射到属性,或者你可以使用框架将对象映射到像Entity frameworkNHibernate这样的表。

While Entity or NHibernate may appear a bit huge swiss knife for a small problem, it's always interesting to built some expertise in it, as the inner concepts are re-usable and it can really speed up development once you got a working setup. 虽然Entity或NHibernate对于一个小问题可能看起来有点巨大的瑞士刀,但它内置一些专业知识总是很有趣,因为内部概念可以重复使用,并且一旦你有了工作设置它就能真正加速开发。

使用foreach语句遍历字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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