【问题标题】:How to write this query using LinQ lambda expression如何使用 LinQ lambda 表达式编写此查询
【发布时间】:2015-02-19 12:52:17
【问题描述】:
SELECT PropertyCommnets.commnet_content, 
       PropertyCommnets.commnet_date, 
       users.user_name, 
       propertycommnets.commnet_id 
FROM   PropertyCommnets  
       INNER JOIN aspnet_users 
               ON propertycommnets.userid = aspnet_users.userid 
       INNER JOIN users 
               ON aspnet_users.userid = users.userid 

我写了这个但不正确:

from a in context.PropertyCommnets 
join b in context.aspnet_Users 
on a.UserId equals b.UserId 
join c in context.Users 
on b.UserId equals c.UserId 
where a.property_id == PropertyId 
select(c.user_name ).FirstOrDefault()

【问题讨论】:

  • “我写了这个但不正确”对不起?

标签: linq join lambda entity


【解决方案1】:

我不明白你最后用你的select 做什么。这不是有效的语法,FirstOrDefault 与您的 sql 查询相比也不正确。

试试这个:

from a in context.PropertyCommnets 
join b in context.aspnet_Users 
on a.UserId equals b.UserId 
join c in context.Users 
on b.UserId equals c.UserId 
where a.property_id == PropertyId 
select new {  
    commnet_content = a.commnet_content,
    commnet_date = a.commnet_date,
    user_name = c.user_name,
    commnet_id = a.commnet_id,
};

但是,这仍然是查询语法而不是方法/lambda 语法。有关系吗?使用连接查询语法更具可读性。

【讨论】:

    【解决方案2】:

    a) 您加入 aspnet_users 是否有特定原因? 你没有使用 aspnet_users.userid

    b) 您的尝试是 Linq SQL 而不是 Lambda 表达式。

    c) 你的用户模型中是否有一个虚拟的 propertycommnets 集合?如果不是我会考虑的。然后您可以简单地调用 user.propertycommnets 和该特定用户的 cmets。

    【讨论】:

      猜你喜欢
      • 2014-06-22
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多