JSON Circular Structure in Entity Framework and Breeze - json

I have a horribly nested Entity Framework structure. A Schedule holds multiple defaults and multiple overrides. Each default/override has a reference back the schedule and a "Type". The Type has a reference back to any defaults or overrides it belongs to. It's messy, but I think it's probably the only way I can do what's required.
This data ends up in a browser in the form of Breeze entities. Before I can process these when saving them back at the server, I have to turn them back into JSON, which unsurprisingly trips the dreaded "Uncaught TypeError: Converting circular structure to JSON".
Now there are a number of perfectly good scripts for removing these circular structures. But all of them seem to replace the circular references with some sort of placeholder so they can be re-created as objects. But of course Entity Framework doesn't recognise these, so can't work with them.
I'm at a loss as to what to do at this point. Simply removing the circular references rather than replacing them doesn't seem to help as it can result in structures shorn of important data.
I've also tried changing my EF queries to only get back specifically the data required, but it insists on giving me absolutely everything, even though Lazy Loading is set to false and I have no .Include statements in my queries. But I feel this is solving the wrong problem, since we're bound to want to deal with complex data at some point.
Is there any other way round this?
EDIT: I've solved this temporarily by investigating the object and removing the circular properties by name. But I'd still like a generic solution if at all possible.

Seems like you are after serialization mode. find out serialization mode in properties in your designer screen and set it to unidirectional. this will solve your serialization issue.
Hope that helps!!!

Not sure I understand the question. You should never experience any kind of circularity issue, regardless of the complexity of your model, with a Breeze SaveChanges call. (Breeze internally unwraps all entities and any circularities before serializing). If you are seeing something different then this would be a bug. Is this the case?

Related

Get Map value like plain old Javascript objects

I'm new to Immutable.js, so this is a very trivial question.
It looks like I can't get a Map value like with plain old Javascript objects, e.g. myMap.myKey. Apparently I have to write myMap.get('myKey')
I am very surprised by this behavior. Is there a reason for that? Is there any extension to Immutable.js which would allow me to type myMap.myKey?
Came back to elaborate on my comment, but SO doesn't allow that after certain time. Converting it into an answer.
The question you have asked has been reciprocated several times with people who start new with immutable, yours truly included. Its on one of the rants I wrote a while ago.
It starts to make sense when you look at it from immutability perspective. If you expose value types as your own properties, they won't be immutable because they are value types and could be assigned to.
Nonetheless, its frustrating to spread these getters all across your components/views. If you can afford it, you should try to use the Record type. It offers traditional access to members (except in IE 8). Better still, you can extend from this type and add helper getters/setters (e.g. user.getName(), user.setName('thebat') instead of user.get('name')/set('name', 'thebat')) to abstract your model's internal structure from your views. However there are challenges to overcome like nested structures and de-serialization of objects.
If the above is not your cup of tea, I'd recommend swallowing the bitter pill :).
I think you are missing the concept Immutable was build:
Immutable data cannot be changed once created, leading to much simpler
application development, no defensive copying, and enabling advanced
memoization and change detection techniques with simple logic.
Persistent data presents a mutative API which does not update the data
in-place, but instead always yields new updated data.
One way or another you may transform Immutable data structures to plain old JS objects as: myMap.toJS()

What is the best practice when you have read-only properties and cannot use the objectdatasource?

I have started a web forms project using nHibernate and objectdatasources; however, I've learned that there are some limitations that I understand but do not know to handle. These limitations include 1) objectdatasources require parameterless constructors and 2) properties of the business object cannot be read-only.
The problem I'm having is that a class in my business layer sets a property that should never change and I'd like to make sure this never happens. I'd like to set that property when the object is created, but make the property read-only so people cannot set it later. I'm not sure it's relevant to the issue, but I am using a repository class as well.
I guess I could simply make the property read/write, but I think that the business layer should enforce the rule of never changing the property. Is there a way to use objectdatasources without relaxing my business rule that a property must be read-only. If I cannot use objectdatasources, is there another best practice that does not include copying the logic of creating objects, setting their properties based on form values and then saving?
Thanks for any insight on this issue. I'm sure people have come across this in the past so I'm just looking for some direction in how to best use data sources for a web forms site. Also, any references to books or articles related to handling not so typical issues would be helpful. It seems like everything I've been looking at has you building CRUD screens...
Sean
You can map the nHibernate to fields. This may help NHibernate : map to fields or properties?
This way you should be able to have RO properties.

Is there a simple Linq to SQL generator with bi-directional serialization attributes?

I'm trying to find a way to generate Linq to SQL classes with bi-directional serialization attributes. Basically I want a DataMember tag (with an appropriate order) on every association property, not just the ones where the class is the primary key (like the Visual Studio generator and SQL Metal do). I checked MyGeneration, but didn't really find anything that worked for me. I thought the T4 Toolbox was going to be my solution, it would be quite easy to modify it to add the attributes, but I get an exception on the calling side of my WCF service, and I've gotten no response back on the issue. I'm about to try installing CodeSmith and using PLINQO, but I'd prefer something free.
I'm pretty close to just writing my own T4 generator, but before I do that, I was hoping to find an pre-built solution to this rather simple problem first.
I ended up writing my own code generator for our L2S classes. We actually generate two sets of classes. One is a "lightweight" set of entities for client application use. These classes have no L2S plumbing. But they have the full datamember attributes with proper order. Then we have our L2S entities, which are strictly for backend use. This has worked out quite well.
Be careful using PLINQO. I've looked at that product extensively. In fact, much of my code generator is based on the code PLINQO generates. However, they have a "major flaw" (their words) in how they have implemented many to many relationships.
You might want to also look at a product named "Reegenerator".
Randy
This turned out to be the solution to my problem. I had just resigned myself to start researching my own generator when I stumbled upon that. It has a bidirectional serialization option and it works great! Here's a link to the author's bog, which contains a great video example of how to get started.

How to save and load different types of objects?

During coding I frequently encounter this situation:
I have several objects (ConcreteType1, ConcreteType2, ...) with the same base type AbstractType, which has abstract methods save and load . Each object can (and has to) save some specific kind of data, by overriding the save method.
I have a list of AbstractType objects which contains various ConcreteTypeX objects.
I walk the list and the save method for each object.
At this point I think it's a good OO design. (Or am I wrong?) The problems start when I want to reload the data:
Each object can load its own data, but I have to know the concrete type in advance, so I can instantiate the right ConcreteTypeX and call the load method. So the loading method has to know a great deal about the concrete types. I usually "solved" this problem by writing some kind of marker before calling save, which is used by the loader to determine the right ConcreteTypeX.
I always had/have a bad feeling about this. It feels like some kind of anti-pattern...
Are there better ways?
EDIT:
I'm sorry for the confusion, I re-wrote some of the text.
I'm aware of serialization and perhaps there is some next-to-perfect solution in Java/.NET/yourFavoriteLanguage, but I'm searching for a general solution, which might be better and more "OOP-ish" compared to my concept.
Is this either .NET or Java? If so, why aren't you using serialisation?
If you can't simply use serialization, then I would still definitely pull the object loading logic out of the base class. Your instinct is correct, leading you to correctly identify a code smell. The base class shouldn't need to change when you change or add derived classes.
The problem is, something has to load the data and instantiate those objects. This sounds like a job for the Abstract Factory pattern.
There are better ways, but let's take a step back and look at it conceptually. What are all objects doing? Loading and Saving. When you get the object from memory, you really don't to have to care whether it gets its information from a file, a database, or the windows registry. You just want the object loaded. That's important to remember because later on, your maintanence programmer will look at the LoadFromFile() method and wonder, "Why is it called that since it really doesn't load anything from a file?"
Secondly, you're running into the issue that we all run into, and it's based in dividing work. You want a level that handles getting data from a physical source; you want a level that manipulates this data, and you want a level that displays this data. This is the crux of N-Tier Development. I've linked to an article that discusses your problem in great detail, and details how to create a Data Access Layer to resolve your issue. There are also numerous code projects here and here.
If it's Java you seek, simply substitute 'java' for .NET and search for 'Java N-Tier development'. However, besides syntactical differences, the design structure is the same.

Creating lightweight Linq2Sql proxy objects

I'm trying to find the most efficient way to send my Linq2Sql objects to my jQuery plugins via JSON, preferably without additional code for each class.
The EntitySets are the main issue as they cause not only recursion, but when recursion is ignored (using JSON.NET's ReferenceLoopHandling feature) a silly amount of data can be retrieved, when I only really need 1 or 2 levels. This gets really bad when you're talking about Users, Roles and Permissions as you get the User's Role, the User's Permissions, the Role's Permissions, and the Role's Users all up in your JSON before it hits recursion and stops. Compare this to what I actually want, which is just the RoleId.
My initial approach was to send a "simplified" version of the object, where I reflect the entity and set any EntitySets to null, but of course in the above example Roles gets set to null and so RoleId is null. Setting only the 2nd level properties to null kind of works but there's still too much data as the EntitySets that weren't killed (the first level ones) repopulate their associated tables when the JsonSerializer does its reflection and I still get all those Permission objects that I just don't need.
I definately don't want to get into the situation of creating a lightweight version of every class and implementing "From" and "To" style methods on them, as this is a lot of work and seems wasteful.
Another option is to put a JsonIgnoreAttribute on the relevant properties, but this is going to cause a nightmare scenario whenever classes need to be re-generated.
My current favourite solution which I like and hate at the same time is to put the classes into opt-in serialization mode, but because I can't add attributes to the real properties I'd have to create JSON-only properties in a partial class. Again, this seems wasteful but I think it's the best so far.
Any suggestions gratefully received!
Have you tried to set the Serialization Mode in the dbml file?
It's a standard property under code generation and when you set it to Unidirectional it won't generate all the additional levels of your table structure. I've used this with silverlight and WCF to send data because the data contracts don't allow for additional levels to be sent (silverlight is very limited on what you can and can't do).
Hope this helps!