日期:2014-05-20  浏览次数:20866 次

在edmx里如何查询匹配外键关联表内的值
有两个用户表,tblA{ aId, Name },tblB{ bId, aId, realName }。其中,A.aId 是主键,B.aId是外键。

将 tblA 和 tblB 放到 edmx 里,两个表都生成了 导航属性 ,tblA 到 tblB 是默认的一对多关系。

我写了这么一个方法来进行查询:

C# code

public List<tblA> Select(int tblAId, string theName, string theRealName)
{
  IQueryable<tblA> q = db.tblA;
  if(tblAId > 0)
    q = q.Where(p => p.Id == tblAId);
  if(!string.IsNullOrEmpty(theName))
    q = q.Where(p => p.Name == theName);
  if(!string.IsNullOrEmpty(theRealName))
    //这里不知道该怎么写了

  return q.ToList();
}




方法的参数里输入了一个 theRealName 字符串,请问,如何进行查询,才能找到 tblB.realName 的匹配项?返回类型是 List<tblA> 会构成障碍吗?


------解决方案--------------------
C# code

public List<tblA> Select(int tblAId, string theName, string theRealName)
{
  IQueryable<tblA> q = db.tblA;
  if(tblAId > 0)
    q = q.Where(p => p.Id == tblAId);
  if(!string.IsNullOrEmpty(theName))
    q = q.Where(p => p.Name == theName);
  if(!string.IsNullOrEmpty(theRealName))
   q=from x in q
     join y in db.tableB
     on x.Id equals y.aId
     where y.realName==theRealName
     select x;

  return q.ToList();
}