这是错误吗?......掉下来了循环引用的理由......如何解决,但? [英] Is this bug ?...got reason behind circular reference ... how to solve but?

查看:173
本文介绍了这是错误吗?......掉下来了循环引用的理由......如何解决,但?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有asp.net的MVC应用程序,其中我的模型有一个像问题可以有多个答案的关系。因此,尽管其创建.dbml文件和类质疑类将包含EntitySet的吧?但在EntitySet的每个对象(指应答对象)将具有属性为问题,因此,框架会自动创建有循环引用和依赖关系。这确实对焦时,我们要序列化问题(列表)的列表生成JSON输出,在控制器的特定操作。如果我们用[ScriptIgnore]属性财产在designer.cs文件问题下课答案(由框架生成,一般人避免去打扰它,我也一样),那么一切运行良好。

我们能否通过使用部分类解决这个问题?但我认为部分属性不会在C#中存在。

我的问题是,这是BUG?或者一些补救措施来解决它?我的关系是:

和错误是:

 在序列化类型'myApp.Models.Question的对象时​​检测到循环引用。


解决方案

这是您正在使用不正确的功能。

您永远不应该序列化的LINQ to SQL(或实体框架)类。尽管微软已经把[DataContract]和这些类的其他属性,他们不应该被序列化。

相反,设计了一组类,这些类正确匹配你希望有什么系列化。例如:

 公共类问题
{
    公众诠释ID {获取;设置;}
    公共字符串文本{获取;设置;}
    公开名单<应答和GT;答案{获取;设置;}
}公共类答
{
    公共字符串文本{获取;设置;}
}

从您的数据库类填充这些类的实例,这些序列化的数据传输,而不是类

顺便说一句,这是数据传输对象模式。

i have asp.net mvc application where my model has a relation like "Question can have multiple answers". So while creating its .dbml file and classes question class would contain the EntitySet right? but each object in the EntitySet (means Answer object) will having the Property as "Question" , so framework automatically creates there circular reference and dependencies. which does comes in focus when we going to serialize the List of Question (List) to generate the json output, for particular action in controller. If we use [ScriptIgnore] attribute to property as "Answers" in "Question" class in designer.cs file (generated by framework, generally people avoids to disturb it and me too) then everything running fine.

Can we solve this by using partial classes? but i think partial properties are not exist in c#.

My question is , is this BUG ? or some remedy to resolve it? my relationship is :

And Error is:

A circular reference was detected while serializing an object of type 'myApp.Models.Question'.

解决方案

This is a feature that you are using incorrectly.

You should never serialize the LINQ to SQL (or Entity Framework) classes. Even though Microsoft has placed [DataContract] and other attributes on these classes, they should not be serialized.

Instead, design a set of classes that correctly matches what you want to have serialized. For instance:

public class Question
{
    public int ID {get;set;}
    public string Text {get;set;}
    public List<Answer> Answers {get;set;}
}

public class Answer
{
    public string Text {get;set;}
}

Populate instances of these classes from your database classes, and serialize these data transfer classes instead.

BTW, this is the Data Transfer Object pattern.

这篇关于这是错误吗?......掉下来了循环引用的理由......如何解决,但?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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