I see two distinct subjects in your question:
- How to manage circular references when serializing to JSON?
- How safe is it to use EF entities as model entities in you views?
Concerning circular references I'm sorry to say that there is no simple solution. First because JSON cannot be used to represent circular references, the following code:
var aParent = {Children : []}, aChild = {Parent : aParent};
aParent.Children.push(aChild);
JSON.stringify(aParent);
Results in: TypeError: Converting circular structure to JSON
The only choice you have is to keep only the composite --> component part of the composition and discard the "back navigation" component --> composite, thus in you example:
class parent
{
public List<child> Children{get;set;}
public int Id{get;set;}
}
class child
{
public int ParentId{get;set;}
[ForeignKey("ParentId"), ScriptIgnore]
public parent MyParent{get;set;}
public string name{get;set;}
}
Nothing prevents you from recomposing this navigation property on your client side, here using jQuery:
$.each(parent.Children, function(i, child) {
child.Parent = parent;
})
But then you will need to discard it again before sending it back to the server, for JSON.stringify won't be able to serialize the circular reference:
$.each(parent.Children, function(i, child) {
delete child.Parent;
})
Now there is the issue of using EF entities as your view model entities.
First EF is likely to using Dynamic Proxies of your class to implement behaviors such as change detection or lazy loading, you have to disable those if you want to serialize the EF entities.
Moreover using EF entities in the UI can be at risk since all the default binder will mapping every field from the request to entities fields including those you did not want the user to set.
Thus, if you want you MVC app to be properly designed I would recommended to use a dedicated view model to prevent the "guts" of your internal business model from being exposed to the client, thus I would recommend you a specific view model.
Best Answer
Yes in general when using Table per Class Inheritance, the derived table has the same primary key as the base table.
I personally prefer table per-hierarchy when possible because it doesn't require an extra join. It does create unused columns in the table which might be cumbersome with large hierarchies, but many modern databases support this scenario adequately (e.g. SQL Server as of 2008 has support for a Sparse Column indicator that lets the DB optimize storage accordingly)