如何使用C#将字典保存到数据库中? [英] How to save a dictionary into a database with C#?
问题描述
我一直在使用以下方式将字典保存到数据库中:
I have been using following way to save dictionaries into the database:
- 将字典转换为XML.
- 将此XML传递到SP(存储过程).
-
在SP中使用:
- Convert the dictionary to XML.
- Pass this XML to a SP(Stored Procedure).
In the SP use:
Select
Key1,
Value1
into #TempTable
FROM OPENXML(@handle, '//ValueSet/Values', 1)
WITH
(
key1 VARCHAR(MAX),
value1 varchar(100)
)
完成.
Done.
有没有一种方法可以将字典保存到数据库而不将其转换为XML?
Is there a way to save dictionaries to a database without converting it to XML?
推荐答案
这取决于是否...
-
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). From my point of view, it breaks the purpose of storing in a SQL database.
您希望人类可以读取数据: XML是一种选择,虽然速度不那么快,有点难以阅读,但仍然不可查询.但是,实现起来非常快.您还可以将结果转储到文件中,并且仍然可读.此外,由于XML是一种普遍的格式,因此您可以与其他应用程序共享数据.
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. 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.
您希望数据可查询.根据您的方式,实现起来可能并不容易.您将需要两个表(一个用于键,一个用于值).然后,您可以编写自己的自定义映射代码以将列映射到属性,也可以使用框架将对象映射到表,例如 NHibernate .
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或NHibernate在解决一个小问题时可能显得有些笨拙,但在其中建立一些专业知识总是很有趣的,因为内部概念是可重用的,并且一旦您建立了可行的设置,它就能真正加快开发速度
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.
这篇关于如何使用C#将字典保存到数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!