这个bug是否有循环引用的原因...如何解决? [英] Is this bug ?...got reason behind circular reference ... how to solve but?

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

问题描述

我有asp.net mvc应用程序,我的模型有一个关系,如问题可以有多个答案。所以在创建其.dbml文件和类问题类时会包含EntitySet对吗?但是EntitySet中的每个对象(意思是回答对象)将使该属性为问题,因此框架会自动创建循环引用和依赖关系。当我们将序列化问题列表(List)来生成json输出,特别是在控制器中的动作时,它将成为焦点。如果我们在designer.cs文件的Question类中使用[ScriptIgnore]属性作为Answers(由框架生成,通常人们也避免打扰它),那么一切正常运行。



我们可以通过使用部分类来解决这个问题吗?但我认为c#中不存在部分属性。



我的问题是,这个BUG?还是一些解决办法呢?我的关系是:



错误是:

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


解决方案

这是您使用不正确的功能。 / p>

你不应该串行化LINQ to SQL(或Entity Framework)类。即使Microsoft已经在这些类上放置了[DataContract]和其他属性,但不应该序列化。



而是设计一组正确匹配您想要的类已经序列化。例如:

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

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

从数据库类中填充这些类的实例,并序列化这些数据传输类。



BTW,这是数据传输对象模式。


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.

这篇关于这个bug是否有循环引用的原因...如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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