Is this bug ?…got reason behind circular reference

2019-04-16 23:49发布

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 :enter image description here

And Error is:

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

3条回答
看我几分像从前
2楼-- · 2019-04-17 00:22

It is a feature :)

The root of the problem is that JSON does not support circular references (although Entity Framework does).

So when you transfer data to the client in JSON you need to decide on the heirarchy you want to use.

Your solution with the [ScriptIgnore] is probably the best way to solve it. Probably best to place it on "Questions" in Answer.

查看更多
虎瘦雄心在
3楼-- · 2019-04-17 00:28

Mark your classes with [DataContract(IsReference = true)] to allow serialization of circular references

查看更多
倾城 Initia
4楼-- · 2019-04-17 00:36

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.

查看更多
登录 后发表回答