tags:

views:

115

answers:

3

Hi,

I have the following model and relationship:

Table: Granddad
GranddadID
GranddadName

Table: Father
FatherID
GranddadID
FatherName

Table: Son
SonID
FatherID
SonName

in the Granddad controller:

public ActionResult Edit(int tmpgranddadid)
{
   var q = (from g in _e.Grandad
           where g.GrandadID == tmpgranddadid
           select g).FirstOrDefault();

   string son_name = q.Father.Son.SonName.ToString(); // <- is wrong, how to do this?

   return View(q);
}

How do you retrieve the value from a linked linked table?

Thank you

A: 

Check out joins:

http://www.hookedonlinq.com/JoinOperator.ashx

UpTheCreek
+1  A: 

Perhaps you want any of the possibly many sons?

q.Fathers.First().Sons.First().SonName.ToString();

Be careful though because First() can throw an exception if a father has no sons. This will handle that case:

string sonName = null;
Father father = q.Fathers.FirstOrDefault();
if (father != null) {
    Son son = father.Sons.FirstOrDefault();
    if (son != null) {
        sonName = son.SonName.ToString();
    }
}
Mark Byers
LOL, thanks Mark :)I reduced it and tried that. However I got an error for: q.Fathers.First().FatherName.ToString().The error is: Object reference not set to an instance of an object.Please help :)Also apart from using First() is there another method I can use to specify [n] son/element? I tried to used ElementAt(0) and I don’t know how to use AsQueryable and it all failed :(Thank you
noobplusplus
I've updated my answer to show you how to handle the case where a father has no sons.
Mark Byers
You might want to check if a reference is loaded with `IsLoaded()` and `Load()` if needed.
Wouter
Thanks mark :) Tried it and got: "Sequence contains no elements." Checked the father table and there are data... Anyideas?
noobplusplus
A: 

Assuming your data source looks something like this:

public class SomeDataSource
{
    public List<Granddad> Granddad;
    public List<Father> Father;
    public List<Son> Son;
}

And assuming you're actually after the first grandson for a granddad then:

var firstGrandson = (from son in _e.Son
               join father in _e.Father on son.FatherID equals father.FatherID
               join granddad in _e.Granddad on father.GranddadID equals granddad.GranddadID
               where granddad.GranddadID == tmpgranddadid
               select son).FirstOrDefault();

if (firstGrandson == null)
    throw new Exception("This granddad has no grandsons.");

string son_name = firstGrandson.SonName;

Is this what you needed?

Codesleuth
Wait a sec, did I get the joins right in this? Damnit.
Codesleuth
Just tested it, works ok.
Codesleuth
Dear Codesleuth. Thanks for that :) Sorry abit slow to try your example I am really new. I tired your code but when I got to "join father in _e.Father on son.FatherID" I can't get the FatherID to show up. In my model view FatherID is kind in "Navigation Properties"
noobplusplus