Entity Framework Serialize entity to json with included related entities - json

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 :)

Related

Freemarker: find specific object in array of arrays

I have a complex many-to-many relationship defined. The cross-reference table is an entity, so I have Contact with a One-To-Many to ContactList, and List with a One-To-Many to Contact List. Contact List contains listID, contactID, and a few Booleans. The relationships seem to work well and on the backend I can get a list of contacts on a review list using the Spring-Data-Jpa findByContactListsIn(Set).
However, I am trying to build a list of contacts in Freemarker, and show whether they were in the current list.
Before I made an Entity out of ContactList, I had a standard Many-To-Many relationship between them, and I was able to do something like this in my .ftl:
<#if list.contacts?seq_contains(contact)>
But I needed to add some data to ContactList specifically, so I needed it to be more complicated. How can I do something similar now? I tried:
<#if list.contactLists?seq_contains(contact)
But of course that always returns false, because it is comparing two different entity types. Is there a way to find if a contact is in one of the contactList objects?
I suppose I could do some back-end trickery, but I am looking for a front-end solution to this.
Don't use ?seq_contains for finding generic object at all. It doesn't call Object.equals, instead it works like the == operator of the template language, which only allows comparing strings, numbers, booleans and dates/times, otherwise it gives you an error. Unfortunately it won't fail in your case, because POJO-s are also strings (and their string value is what toString() returns). This is an unfortunate legacy of the stock ObjectWrapper (scheduled to be fixed in FM3); not even a quirk in the template language. Ideally you get an error there. Instead, now it silently compares the return value of the toString()-s...
Your data-model should already contain what the template should actually display. FTL is not a programming language, so if you try to extract that from the data-model in it, it will be a pain. But, that the data-model contains that data can also mean that some objects in the data-model have methods that extract the data you need. As a last resort, you can add objects that just contain helper methods.
Update: Returning to ?seq_contains, if you need the Java semantics and list is a Java Collection, you can just use the Java API: list?api.contains(contact).

Deserializing json and resolving JPA entities

I have two entities X and Y with the relation #ManyToMany. X has a list of Y's, let's call it yList. Both X and Y has other class members as well (they are not important).
I am using Hibernate as JPA provider, and jackson-databind / jackson-annotations for things like serialization and deserialization.
Now, the following json is received from the client. It has all the fields of X, but only a list of id's for Y. As a concrete example, X could be Person and Y could be Country. And the many-to-many relation captures which countries have been visited by whom.
{
name: 'Bob Dylan',
age: '74',
visitedCountryIds: ['45', '23', '85']
}
When deserializing this json, I want to populate all the fields of the entity X, including yList, such that the elements of yList are resolved by looking up these entities in the database.
My idea so far is to deserialize yList by writing a custom subclass of JsonDeserializer, and have it perform the lookup by id.
Is this a reasonable approach?
You could use #JsonCreator (as already suggested by Uri Shalit) or just a setter method for your property in which you would do necessary lookups from the database.
However, if you have many entities (and associations) for which you want to do this, then this could be a repeated boilerplate code. Also, if implemented in entity classes directly, it would pollute them with database lookup code (readability, SRP, etc).
If you want some generic approach to this, then I think you are on a good way; custom deserializer is the place to implement it.
If I were to implement the generic approach, I would probably introduce a custom annotation which I would place on the association definition together with standard JPA annotations. For example:
#MyCustomJsonIds("visitedCountryIds")
#ManyToMany(...)
private List<Country> countries;
Then, in the deserializer, I would query for the presence of those annotations to dynamically determine what needs to be looked up from the database.
Another option is to create a constructor that that accepts those parameters, annotate it with #JsonCreator and have the constructor perform the lookup from the database, this way you don't need to write a specific deserializer.

Best way to convert Doctrine 2 entity persistent collection to array with Zend Framework 2

What is best way (easy) to convert Doctrine 2 entity persistent collection to array with Zend Framework 2? I want convert to array and later output it with JsonView. I can write function which use get_object_var but it is a problem when entity has next entity collection.
Regards.
Not sure about Zend, but in SF2 + Doctrine you can use getValues() method.
$asArray = $persistentCollection->getValues();
I'll decouple the answer in 2 parts, mainly because you haven't clarified enough if you want to solve purely the PersistentCollection or the entire graph serialization.
1- Assuming you already know how to solve Entity's serialization, the PersistentCollection can be turned into an array of Entities by calling toArray() method.
2- Assuming you don't, I suggest you to either use a pre-built library like JMS Serializer.
If you want to create your own by hand, use the ClassMetadata instance that can be extracted from EntityManager->getClassMetadata(get_class($someEntity)) and iterating through fieldMappings and associationMappings properties.

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

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.

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.