I have a Linq to SQL class.
There is a one to many relationship in my database.
The relationship maps correctly in the designer, and an EntitySet<>
property is created in the designer.
When I run the code, the EntitySet<>
does not populate with any data, even though there are associated records, they do not populate into the EntitySet<>
Am I missing some property or setting? Do I have to write the query myself? I feel like I'm missing something obvious.
Here is the Designer code:
[Association(Name = "Bar_Foo", Storage = "_Foo", ThisKey = "ID", OtherKey = "BarID")]
[DataMember(Order = 15, EmitDefaultValue = false)]
public EntitySet<Foo> Foos
{
get
{
if ((this.serializing && (this._Foo.HasLoadedOrAssignedValues == false)))
{
return null;
}
return this._Foo;
}
set
{
this._Foo.Assign(value);
}
}
This is the code where I am trying to access the EntitySet<>:
partial void OnCreated()
{
foreach (Foo foo in Foos)
{
foo.DoSomething();
}
}
More information about my situation:
So, from above I have a class Bar with a collection of Foo. What I am trying to do is pass Bar to a UI via a WCF service. Following is my primary service call:
public class TheService : ITheService
{
public List<Bar> GetBars()
{
try
{
using (var db = new BarDataContext())
{
List<Bar> Bars = new List<Bar>();
Bars = (from B in db.Bars
select B).ToList();
return Bars;
}
}
catch (Exception ex)
{
throw new FaultException(ex.Message + " Something in GetBars() Stack Trace: " + ex.StackTrace);
}
}
}
Currently, when the service returns the Bars the Foos inside each Bar is null.
If I create a property in Bar that looks at Foos, I get a null reference exception.
I try to run a query in the OnCreated method to fill Foos, the ID of the current Bar is 0.
Updated Query that still doesn't work:
using (var ctx = new BarDataContext())
{
List<Bar> Bars= new List<Bar>();
Bars= (from B in ctx.Bars
select B).ToList();
foreach (Bar bar in Bars)
{
bar.Foos= (from B in ctx.Bars
where B.ID == bar.ID
select B.Foos).SingleOrDefault();
}
return Bars;
}
This code generates a null reference exception when I try to query Foos from Bar.
EDIT:
The code above magically stopped throwing null reference exceptions, dunno why. I find it interesting that you don't even need to set bar.Foos in the above query, you can put the Foos query into a variable that never gets used and it will fill in the Bar.Foos property, just because you looked at Foos. Reminds me of schrodinger's cat.