实体框架:连接两个表和 where 子句

Àle*_*lex 27 c# postgresql entity-framework entity-framework-core .net-core

我在使用实体框架和 PostgreSQL 时遇到问题,有人知道如何连接两个表并将第二个表用作 where 子句吗?

我想在实体框架中执行的选择将在 SQL 中:

SELECT ai.id, ai.title, ai.description, ai.coverimageurl 
FROM app_information ai 
INNER JOIN app_languages al on al.id = ai.languageid
WHERE al.languagecode = 'es'
Run Code Online (Sandbox Code Playgroud)

目前我有这个

var appInformationToReturn = context.app_information
     .Join(
          context.app_language,
          ai => ai.languageid,
          al => al.id,
          (ai, al) => new AppInformation()
          {
               id = ai.id,
               title = ai.title,
               description = ai.description,
               coverimageurl = ai.coverimageurl
          })
     .Where()
     .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

我不知道如何构建该where条款。

Afs*_*ani 38

像这样:

var appInformationToReturn = context.app_information
     .Join(
          context.app_language,
          ai => ai.languageid,
          al => al.id,
          (ai, al) => new
          {
               id = ai.id,
               title = ai.title,
               description = ai.description,
               coverimageurl = ai.coverimageurl,
               lang = al.languagecode
          })
     .Where(x => x.lang == "es")
     .Select(x => new AppInformation()
     {
          id = x.id,
          title = x.title,
          description = x.description,
          coverimageurl = x.coverimageurl
     })
     .FirstOrDefault(); 
Run Code Online (Sandbox Code Playgroud)

更新(2023/03/26):最近这个答案得到了一些关注,所以我决定更新并将其与@Serge 提供的答案的第一部分结合起来。

var item = (
     from ai in context.app_information
     join al in context.app_language on ai.languageid equals al.id 
     where (al.languagecode == "es")
     select new AppInformation 
     {
          id = ai.id,
          title = ai.title,
          description = ai.description,
          coverimageurl = ai.coverimageurl
     }).FirstOrDefault(); 
Run Code Online (Sandbox Code Playgroud)


Ser*_*rge 5

尝试这个:

var item = (
    from ai in context.app_information
    join al in context.app_language on ai.languageid equals al.id 
    where (al.languagecode == "es")
    select new AppInformation 
    {
        id = ai.id,
        title = ai.title,
        description = ai.description,
        coverimageurl = ai.coverimageurl
    }).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

或者尝试更短

var item = context.app_information
    .Where(ai => ai.app_language.languagecode == "es")
    .Select(ai => new AppInformation 
    {
        id = ai.id,
        title = ai.title,
        description = ai.description,
        coverimageurl = ai.coverimageurl
    })
    .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

  • 在第二个代码部分。加入在哪里?您假设表之间存在关系。我知道应该有关系,但他要求加入。 (2认同)
  • 这是不一样的。简单地说,您假设 app_information 实体类中有 app_language 变量。他询问使用 join 这意味着 app_information 中的其他实体可能没有这样的变量。 (2认同)