且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

这个bug是否有循环引用的原因...如何解决?

更新时间:2022-11-02 19:12:01

这是您使用不正确的功能。 / 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.