EF entities that contain relations (PKs,FKs) cannot be Json-ed? - json

I have build a very very simple database schema as
**Tickets**:
TicketId (PK)
AreaId (FK)
SeverityId (FK)
AssigneeId (FK)
**Areas**:
AreaId(PK)
AreaName
**Severities**:
SeverityId(PK)
SeverityName
**Assignees**:
AssigneeId(PK)
AssigneeName
I create the Entity Model and in the TicketController I am trying to retrieve and Json the data inside the Tickets table.
[HttpPost]
public ActionResult Index([DataSourceRequest]DataSourceRequest result)
{
var tickets = db.Tickets.Include(t=> t.Areas).Include(t=> t.Assignees).Include(t=> t.Severities)
DataSourceResult result = tickets.ToDataSourceResult(request);
Return Json(result);
}
For a reason that I cannot understand when I Json the result in order to pass it to a KendoUiGrid in the view, I get the "circular reference error". I see no circular reference in my tables/entities relations!!
In the Kendo documentation I read this
If you decide to use the Kendo UI JavaScript libraries directly,
returning JSON is simple. You just need to defined a controller
method and call this.Json on your return result. Provided .NET can
serialize your response, this is all there is to it.
Does all the above mean that in reality I cannot Json entities that come from sane database schemas with primary/foreign keys?
Thanx in advance

Create a flat Model class and pass the model to Json and Grid. You will have to populate the model a little more manually than what you are trying to do here, but there are other benefits to having a model that you will discover later. The circular reference is because of the navigational properties of your EF classes. In MVC the model does not mean the data model classes, but new ones you create. Done right the new model should do most of the work, validation, translation, etc. The controllers just passes things around, the view just renders. Hope this helps!

Try disabling lazy loading. May be it's trying to serialize everything in the DB to JSON.

Related

Entity Framework Serialize entity to json with included related entities

I have a User entity with too many relations to other entities in the system. And I am using AngularJs and want to serialize the User entity to json with only the included entities.
Here is my select statement:
var users = unc.Users.Include("Profile").ToList();
when serializing this to json it will always result into
The operation cannot be completed because the DbContext has been disposed
I used to solve this problem by just selecting every column I need in my view like this:
var users = unc.Users.Select(x => new { x.Id ,x.Username,Role=x.Role.Name,x.Email,x.Profile.Name,x.UpdatedAt,x.CreatedAt}).ToList();
but this is too hard and much code to write. I am looking for the ideal or a better solution.
Thanks
I'v found a decent solution here.
https://efjson.codeplex.com/
This will serialize your entity without including related entities unless you wanted to include those entities. This will avoid entering into circular loops caused by entities calling each other back through reversed attributes.
Also serializing related entities you want will make it easy to serialize an entity and through the JSON back to scripts like AngularJs.
Hope this will make other people happy too :)

How to serialize transient fields in the model via FlexJson?

I am using Play Framework to expose REST API, which returns some JSON objects.
To simplify the API usage, I would like to return a "calculated" field in the response.
Unfortunately, in my tests, while FlexJson does not ignore the transient model fields completely, but always sets them to 'null'.
More details:
In the model class, I define:
#Transient
public String currencyName;
The only constructor of the class set the value to "dollar" (for debugging purposes):
this.currencyName = "dollar";
When serializing the class using FlexJson, when the 'currencyName' field is not specified in the include/ exclude - the result always looks like:
"currencyName":null
Any idea what got wrong, and how to get the field value serialized into JSON?
Thanks in advance.
By definition if your field is transient it will not be serialized. Perhaps this field should not be transient in your application if the state matters.

Dojo enhanced datagrid and nested json string

I am having great difficulty in feeding my json string to my dojo enhanced datagrid. Now basically I have a person entity which has a date-of-birth and a nationality. On the person Table nationality is a forign Key.
I am using spring 3.0 and here is my controller logic for producing the json string.
uiModel.addAttribute("studentasJSON", new JSONSerializer().serialize(students));
//students is a list of Student objects
Now if I print out the json string for one student we have this.
[{"class":"tt.edu.sbcs.model.Student","comment":null,"dateOfBirth":{"class":"java.util.GregorianCalendar","firstDayOfWeek":1,"gregorianChange":-12219292800000,"lenient":true,"minimalDaysInFirstWeek":1,"time":1069041600000,"timeInMillis":1069041600000,"timeZone":{"DSTSavings":0,"ID":"America/La_Paz","class":"sun.util.calendar.ZoneInfo","dirty":false,"displayName":"Bolivia
Time","lastRuleInstance":null,"rawOffset":-14400000}},"ethnicOrigin":null,"firstName":"Goat","gender":"Male","id":5487,"lastName":"Dog","legacyID":null,"maritalStatus":"Single","nationality":{"class":"tt.edu.sbcs.model.Country","code":"BB","id":1,"name":"Barbados","version":262},"nativeLanguage":null,"otherName":"","photo":null,"religion":null,"title":{"class":"tt.edu.sbcs.model.Title","id":1,"name":"Mr.","version":0},"uniqueIdNumber":null,"version":0}]
This is where it gets complicated. The dojo enhancedgrid requires "dateOfBirth":"2003-11-17". Similarly,"nationality":"Barbados" and NOT the fully serialized Object. However, http://dojotoolkit.org/reference-guide/dojo/store.html speakes about the querying an existing datastore, but its not very clear how to use it. Can someone please advise?
I saw on http://forum.springsource.org/showthread.php?103331-Best-practices-with-Spring-Roo-JSON-and-Ajax they used the query attribute of the dojo enhanced grid to some how query the string. Something like
<table dojoType="dojox.grid.DataGrid"
jsid="grid" id="grid" class="grid" autoHeight="15" noDataMessage="Sorry, there is no data available."
store="jsonStore" query="{ name: '*' }" rowsPerPage="20" rowSelector="20px">
Can someone please advise on the use of the query attribute. It is impractical to manipulate the string after it is generated as there will be thousands of tuples and linkages to arbitrary entities in my system.

MVC3 JsonResult: How to disable serialization of child objects?

I am using ASP.NET MVC3 and one of my action methods is set up to return a Json response:
[HttpPost]
public JsonResult AddUser(User user)
{
... do something to user and return it ...
return Json(user);
While processing with Entity Framework, the user object gets a few child objects. Json serializer is likely to be unable to cope with the entire object graph, and returns InvalidOperationError error (about a circular reference being identified).
I do not need any of the child objects actually, and I would like to get user serialized without child objects. How I can achieve this?
Thank you in advance!
You can use the ScriptIgnoreAttribute to tag members you don't want serialized.

Create a List-type view dynamically from a Json object in MVC3

I have a controller that access a WCF service which returns a Json object (collection). All rows are of same type, but at different calls the row stricture is different (the return object comes from a user-built sql query, executed with executeReader and serialized as Json
So I don't know the row structure upfront.
What I need is an easy way to pass this Json string to something which will generate a view of type list on the fly for it. Doesn't matter formatting, etc, just should be output easily as a table.
Does anyone knows how can I accomplish this?
Another option might be to have something that generate the view on the fly for a IEnumerable of anonymous objects (since using this I could convert the json to a list of anonymous)
EDIT
I found something that does pretty much what I need, except it display metadata about passed object.
It is preetyPrint.js, and I integrated it in my page as below:
In my controller I set the result json object to ViewBag.Result, and in the view I used this code:
<script src="#Url.Content("~/Scripts/prettyprint.js")" type="text/javascript"> </script>
<div id="resultGrid"></div>
<script>
var resultObject = #Html.Raw(ViewBag.Result);
var ppTable = prettyPrint(resultObject);
document.getElementById('resultGrid').appendChild(ppTable);
</script>
Does anyone knows such script that actually "dump" the data instead of metadata?
Thanks.
You should create a class to deserialize to if you know the properties of the row. Then use the JavaScriptSerializer class to deserialize to a list of your new class you created. Then you can take a look at the WebGrid class to output the HTML, or just manually iterate over the property metadata in your view.
Creating a custom class will provide you the ability to use metadata to control formatting or other display attributes of the output.
If you cannot create a custom class, you can always use Json.NET or the JavaScriptSerializer to deserialize to a list of dictionary objects or ExpandoObject / Dynamic's or something. Then you would have to manually write something to iterate the keys I think. The ModelMetadataProvider in MVC may be able to handle these allowing you to just iterate the properties in your view code.