我有以下模型和关系:
Table: Granddad
GranddadID
GranddadName
Table: Father
FatherID
GranddadID
FatherName
Table: Son
SonID
FatherID
SonName
爷爷控制器中的:
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);
}
如何从链接的链接表中检索值?
谢谢
答案 0 :(得分:1)
也许你想要任何可能很多的儿子?
q.Fathers.First().Sons.First().SonName.ToString();
要小心,因为如果父亲没有儿子,First()可以抛出异常。这将处理这种情况:
string sonName = null;
Father father = q.Fathers.FirstOrDefault();
if (father != null) {
Son son = father.Sons.FirstOrDefault();
if (son != null) {
sonName = son.SonName.ToString();
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
假设您的数据源看起来像这样:
public class SomeDataSource
{
public List<Granddad> Granddad;
public List<Father> Father;
public List<Son> Son;
}
假设你实际上是在孙子的第一个孙子之后那么:
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;
这是你需要的吗?