0

I'm making a JSON from my Database made with LINQ to SQL. I've set up Serialization Mode Unidirectional (so I can serialize data), and once I query my Object (User) I convert it to JSON:

[WebMethod]
public User GetUserByID(int ID)
{
    User user = db.User.Where(p => p.ID == ID).FirstOrDefault();
    var json = JsonConvert.SerializeObject(user, new IsoDateTimeConverter());
    return user;
}

The problem is that on the resulting JSON, the nested data/objects (i.e. the relationship I have for that Object to others Object/Tables) are null.

So, for example, if I have 3 Phone numbers (1-n relationship) for that user, instead of retrieve a JSON array with these (3) numbers, it puts:

"Phones": null,

how can I "force" the User to be queried with all data/relationship inside it?

And if I do this query (for example) before serialize:

var phones = m_oAlumno.Telefono.ToList();

it says "Self referencing loop detected for type 'User'."

markzzz
  • 45,272
  • 113
  • 282
  • 475

1 Answers1

0

In LINQ to SQL you can load referenced entities using DataLoadOptions.

var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<User>(u => u.PhoneNumber);
db.LoadOptions = loadOptions;

Where PhoneNumber is an entity that references User and assuming db is your linq data context.

Nikhil Vartak
  • 4,822
  • 3
  • 23
  • 31
  • Uhm, but how can I "automate" this process? If I add a new table in the future, I'd like to "not" load manually in the code the new table :O – markzzz Sep 30 '15 at 10:21
  • And anyway, it says the same: `Self referencing loop detected for type 'User'.` I can use `PreserveReferencesHandling.Objects` but it adds futile fields :( – markzzz Sep 30 '15 at 10:22