tags:

views:

82

answers:

2

Hello! I have a Person class being generated by LINQ to SQL, which has a Rota association property to a Rota class.

However when trying to access the Rota property on Person (for instance calling db.People.First().Rota), a NullReferenceException in thrown in the generated LINQ to SQL class's property: get { return this._Rota.Entity; }

The _Rota field is being set to default(EntityRef<Rota>) in the constructor for Person.

When I hover over the Person instance in Visual Studio, the DataTip shows the Rota property as existing and being properly populated. I can't work out why it isn't being initalized in the code.

I've tried regenerating the generated code, and other associations are working fine.

Thanks in advance

A: 

Eventually figured out what's causing this.

In the Rota object's OnLoaded method, I was trying to add an object to a list which I hadn't initialized yet (duh). The list is a member of the rota object.

Clearly this should make everything go boom, but it was throwing the error in an odd place which made it hard to debug.

Any errors thrown in custom OnLoaded code will be thrown on the line where the Entity is first accessed (at least in lazy-loaded entities). Could I have debugged this more easily?


Edit: Presumably I couldn't have debugged this any easier, because my OnLoaded() method is called from LINQ to SQL's external code, thus breaking the call stack?

Tom Gilder
A: 

Well I guess based on your above post this might not be the exact answer, but I was going to suggest that you need to ensure that a Person's Rota was even being retrieved at the same time (it wouldn't have been retrieved by default). You would need to configure querying across relationships.

As for your comment about OnLoaded, it's called only after data is loaded into it - that is, when it's retrieved via a SELECT rather than "lazy loading". Perhaps you wan this code you mention in the OnCreated partial method instead? This is called on instantiation (and thus loading) and also deserialization.

Reddog