通过WCF发送实体框架实体:如何防止导航字段的序列化? [英] Sending Entity Framework entities over WCF: how to prevent serialization of navigation fields?

查看:87
本文介绍了通过WCF发送实体框架实体:如何防止导航字段的序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在通过WCF导航属性发送Entity Framework生成的实体时,我有一个问题。我有一个证券数据库用于存储财务数据和两个表:



股票:Id,Symbol,CompanyName,ExchangeName

选项:Id,StockId,OptionType,Strike



我为此数据库创建了一个实体框架模型。然后我创建了WCF服务,向客户端公开生成的库存选项 EF实体。



我生成的实体库存具有导航属性 EntityCollection< Option>选项
当尝试从WCF服务向客户端返回库存实体时,我得到一个 SerializationException :WCF不能序列化选项导航属性,因为数据库连接已经关闭。



我可以调用选项打开数据库连接以填充选项属性的.Load()方法,但如果我不想加载完整的对象,该怎么办股票实体的图表

解决方案

一段时间。



首先,我变得懒惰加载。但是在对象图中我仍然遇到周期问题。

然后,我将所有实体的 [DataContract(IsReference = true)] 标签。这是有效的,但是我仍然对非规范化数据库做了很多性能问题。
最后,我打破了dtos,并使用AutoMapper来填充它们。



我的同事之一告诉我从一开始就这样做,而我应该刚刚听他的话。自己一个忙,不要犯同样的错误。



修改

我忘了提及我的问题反序列化属性类型为 ICollection< T> 的问题。这些将反序列化为数组。不知何故 T [] 实现 ICollection< T> 添加删除会抛出异常。这是使用DTO的另一个原因。


I have a problem when sending Entity Framework-generated entities with navigation properties over WCF. I have a Securities database for storing financial data and two tables inside it:

Stock : Id, Symbol, CompanyName, ExchangeName
Option: Id, StockId, OptionType, Strike

I created an Entity Framework model for this database. Then I created WCF service which exposes generated Stock and Option EF entities to the clients.

My generated entity Stock has navigation property EntityCollection<Option> Options. When trying to return Stock entity from WCF service to the client, I get an SerializationException: WCF cannot serialize Options navigation property because database connection has been already closed.

I can call Options.Load() method when database connection is opened to fill Options property, but what should I do if I don't want to load full object graph for Stock entity?

解决方案

I've fought with this one for a while.

First, I turned lazy loading off. But I still had problems with cycles in my object graph.
Then, I put [DataContract(IsReference = true)] tags on all of my entities. That worked, but I still had a lot of performance issues do to a denormalized database. Finally, I broke down and make dtos and I use AutoMapper to populate them.

One of my coworkers told me to do this from the beginning, and I should have just listened to him. Do yourself a favor and don't make the same mistake that I did.

Edit
I forgot to mention that I had issues deserializing entities that has properties of type ICollection<T>. These will deserialize as arrays. Somehow T[] implements ICollection<T> but Add and Remove will throw exceptions. This was another reason to use DTOs.

这篇关于通过WCF发送实体框架实体:如何防止导航字段的序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆