是否有一种简单的方法可以序列化/反序列化 EF 容器中的实体集合?
我似乎突然想到了以下一系列事件:
- 我创建了一个模型。
- 我将数据加载到模型中。
- 我更改了模型,在往返过程中丢失了数据。
- 我将数据重新加载到模型中,为此编写了大量样板代码。
我能想到的选项:
- (A) 在更改模型之前让 SSMS 生成脚本。
- (二)使用 TSQL for xml 功能可将我的数据转换为 XML(我必须了解如何 这样做,但似乎是可能的)。
- (C) 改变EF代码生成 放置 XML 序列化属性
- (D) 有一个 专家告诉我为什么我的方法是错误的并让我改正,所以这 问题已无效
The following sequence of events seems to crop up for me:
- I create a model.
- I load data into the model.
- I change the model, losing the data in the round trip.
- I reload data into the model, writing alot of boilerplate code to do so.
Options I can think of:
- (A) have SSMS generate scripts before I change the model.
- (B) using
TSQL for xml feature to get my data into XML (I'd have to learn how
to do this but it seems possible). - (C) alter the EF code generation
to place XML serialization attributes - (D) have an
expert tell me why my approach is wrong and set me straight so this
problem is nullified
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一旦您序列化并共享/存储该数据,您基本上就拥有了一份合同。因此,如果您预见模型版本控制存在任何问题,我将创建一个单独 DTO 模型以用于序列化目的。然后,即使您的数据库模型发生变化,您也可以将数据重新加载到 DTO 中。显然,您需要将数据库模型映射到数据库模型或从数据库模型映射,但这通常非常简单。
简而言之,我认为问题在于模型的双重使用:
当以下方法效果更好时:
可以通过调整标记为
*
的链接中的代码来单独处理数据库模型的版本控制现在您 还可以处理这种情况下的存储更改,甚至支持多个 DTO 模型(用于不同的目的,或不同/不兼容的修订版)。
每当序列化变得棘手时,最简单的解决方法通常是:引入 DTO
Once you have serialized and shared/stored that data, you essentially have a contract. Therefore, if you foresee any issues of versioning the model, I would create a separate DTO model for serialization purposes. Then you can reload the data into your DTO even if your DB model changes. You will obviously need to map the DB model to/from the DB model, but that is usually pretty trivial.
In short, I think the problem is the dual use of the model:
When the following works better:
Now you can handle versioning the DB Model separately, by tweaking the code you have in the link marked
*
You can also handle storage changes in this scenario, or even support multiple DTO models (either for different purposes, or different/incompatible revisions).
Whenever serialization gets tricky, the simplest fix is usually: introduce a DTO