Reputation: 12295
So I have a couple of tables in a linq-to-sql dbml file:
I have set up a WCF REST get endpoint to user. I cannot get it to pass back a JSON structured like this:
{
ID: '123',
Username: 'fdsaf',
...
Role:
{
ID: '123',
...
}
}
If I set the DBML serialization mode from "None" to "Unidirectional," I can get the user object without the role. If I leave the serialization mode on none and remove the association, I can also get the user object. As a sanity check, I can also get the role with no user. As soon as I try to include a reference, it attempts to serialize twice (in the debugger) and I get the following error after what appears to be a successful function call on the client:
Additionally, I can get what I'm looking for if I open the association and turn the child property access to internal. However, I will sometimes want to pass back roles with collections of users, so this will not be sufficient.
I include this piece of information because it seems to indicate that the serializer is trying to serialize User > Role > User > Role ... etc., which is obviously insufficient. But there must be a middle ground between a circular and a zero-level-deep reference.
Code below:
using (DataContext context = new DataContext())
{
DataLoadOptions opts = new DataLoadOptions();
opts.LoadWith<User>(u => u.Role);
context.LoadOptions = opts;
return context.Users
.Where(u => u.ID == id)
.Where(u => u.Hash == hash)
.FirstOrDefault();
}
Upvotes: 3
Views: 1222
Reputation: 545
I would create a mapped object instead of a user and give it an array of roles, Mainly because you are passing back a raw data object which includes the password and raw hash of a user. You can then hide these in the mapping
Have one model for each, UserObject with a child of Roles and a RolesObject with a child of User.
Alternatively, have a property that you can serialize on each that will return pseudo objects so roles could be an array of id/strings and so could users (then you ignore serialization on the relationship and serialize that instead, no circular reference problems)
Upvotes: 1