使用LINQ连接两个表,并从两个表中获取少量列

时间:2014-04-14 06:18:14

标签: c# linq entity-framework

public IQueryable GetAllCountry()
{
    using (Context context = new Context())
    {
        var countries = context.COUNTRY.Select(c => new
         {
             country = new
              {
                  ID = c.ID,
                  Description = c.DESCRIPTION,
                  Currency = c.CURRENCY.CURRENCY_SYMBOL,
                  Language = context.LANGUAGE.Select( l => new { lang = l.COUNTRY.CURRENCY_ID})
               }
             });

                return countries;
            }

        }

上面是一个LINQ查询,它从两个表COUNTRY和LANGUAGE中获取结果。一个国家可以有很多语言。我想获取特定COUNTRY的所有LANGUAGE。我怎么能这样做?

当我运行查询时,我得到以下结果:

Argentina  -->System.Collections.Generic.List`1[<>f__AnonymousType0`1[System.Nullable`1[System.Int32]]]
Australia  -->System.Collections.Generic.List`1[<>f__AnonymousType0`1[System.Nullable`1[System.Int32]]]
Bangladesh  -->System.Collections.Generic.List`1[<>f__AnonymousType0`1[System.Nullable`1[System.Int32]]]
Bahrain  -->System.Collections.Generic.List`1[<>f__AnonymousType0`1[System.Nullable`1[System.Int32]]]
Bahamas  -->System.Collections.Generic.List`1[<>f__AnonymousType0`1[System.Nullable`1[System.Int32]]]
Brunei  -->System.Collections.Generic.List`1[<>f__AnonymousType0`1[System.Nullable`1[System.Int32]]]

2 个答案:

答案 0 :(得分:0)

您正在阅读COUNTRY.CURRENCY_ID表中的LANGUAGE。你似乎不需要那种信息。如果您的LANGUAGECOUNTRY表有关系,您可以说:

public IQueryable GetAllCountry()
{
    using (Context context = new Context())
    {
        var countries = context.COUNTRY.Select(c => new
        {
            country = new
            {
                ID = c.ID,
                Description = c.DESCRIPTION,
                Currency = c.VFS_CURRENCY.CURRENCY_SYMBOL,
                Language = c.Languages.Select( l => new { l.Description /* desired field from LANGUAGE */ } )
            }
        });
        return countries;
    }
}

答案 1 :(得分:0)

我希望它会对你有所帮助:

 public IQueryable GetAllCountry()
 {
    using (Context context = new Context())
    {
    var countries = context.COUNTRY.Select(c => new
     {
         country = new
          {
              ID = c.ID,
              Description = c.DESCRIPTION,
              Currency = c.VFS_CURRENCY.CURRENCY_SYMBOL,
              List<Language> = context.LANGUAGE.Where( l => l.Currency_ID ==c.COUNTRY.CURRENCY_ID}).ToList()//I just guess your LANGUAGE table has Currency_ID column
           }
         });

            return countries;
        }

    }