EF6:如何避免循环引用? [英] EF6: How to avoid circular reference?

查看:285
本文介绍了EF6:如何避免循环引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用ASP.NET Web API进行JSON序列化期间,避免使用Entity Framework 6进行循环引用的可能性有哪些?

What are the possibilities to avoid circular reference with Entity Framework 6 during JSON serialization with ASP.NET Web API?

我首先为数据库Entity Framework 6生成了一个edmx(实体数据模型)文件.我尝试使用ASP.NET Web API构建API.当我尝试在控制器中返回JSON对象时,由于循环引用,我遇到了序列化的运行时异常.

I generated a edmx (Entity Data Model) file for Entity Framework 6, database first. I try to build an API with ASP.NET Web API. When I try to return my JSON object in my controllers I get a runtime exception of serialization because of circular reference.

实际上,当我仔细检查数据库和实体时,我看到一个实体包含一个列表,另一个实体包含了先前实体的列表.假设我有一个包含作者的图书实体,每个作者实体均包含一个图书列表.这是相对数据库的常见问题,但无法在JSON序列化中解决(或无法为.NET序列化器解决).

Indeed when I double check my database and my entities I see one of my entity contains a list another entity that contain a list of my previous entity. let say I have a book entity that contains authors and each author entity contains a list of books. This is something common with relative database but impossible to resolve in JSON serialization (or impossible to resolve for the .NET serializer).

我不想更改数据库,但已经准备好将错误列表分解为实体或edmx文件.我该怎么办?

I don't want to change my database but I'm ready to break the wrong list into my entities or edmx file. What can I do?

我尝试过的事情:

我已经尝试了由创建新模型或实体以及使用映射工具组成的解决方案(

I already tried the solution that consist of creating new models or entities and using a mapping tool (http://www.codeproject.com/Articles/292970/Avoiding-Circular-Reference-for-Entity-in-JSON-Ser or the solution explained by by Shawn Wildermuth on Pluralsight).

与实际的解决方案相比,此解决方案听起来更像是一种解决方法.它应该在edmx文件或Entity Framework中存在某些内容,以告诉JSON序列化程序哪些可能导致循环引用,哪些可以并且必须序列化,哪些不能序列化,对吗?

This solution sounds more like a workaround than a real solution. It should exist something in edmx file or in Entity Framework to tell the JSON serializer what can cause circular reference, what can and must be serialized and what cannot be serialized, right?

推荐答案

从技术上讲,直接序列化域模型没有问题.为了避免循环引用,您不能使用延迟加载.您必须控制加载.这样做

There is technically no problem to serialize the domain model directly. To avoid circular reference you cannot use lazy loading. You must keep control of the loading. To do so

  1. 在每次收集模型之前删除虚拟对象(采用代码优先方法)
  2. 将延迟加载配置设置为false(采用数据库优先方法)

这篇关于EF6:如何避免循环引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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