【问题标题】:Convert SQL query to LINQ query but only select specific values to return将 SQL 查询转换为 LINQ 查询,但只选择要返回的特定值
【发布时间】:2023-03-30 02:16:01
【问题描述】:

我自己有一个 SQL 查询

SELECT follow_up_date, MAX(last_contact_date) AS last_contact_date
FROM db_accounts_last_contacts p
GROUP BY p.account_id

我试过了

var queryTest = context.db_accounts_last_contacts.SqlQuery(@"SELECT follow_up_date, MAX(last_contact_date) AS last_contact_date
FROM db_accounts_last_contacts p
GROUP BY p.account_id");

但我收到此错误。

The data reader is incompatible with the specified 'dbModel.db_accounts_last_contacts'. A member of the type, 'id', does not have a corresponding column in the data reader with the same name.

我不想提取所有信息,因为此表可能稍后会更新,我只想提取这两列

【问题讨论】:

  • 该 SQL 查询是否有效?由于它不在聚合函数中,您不需要在 group by 子句中包含 follow_up_date 吗?

标签: c# mysql sql-server linq


【解决方案1】:

我认为您正在尝试使用表本身访问数据库表。 并且您在 p 变量之前缺少“AS”。 尝试以下方法:

    var queryTest = context.ExecuteSqlCommand(@"SELECT follow_up_date, MAX(last_contact_date) AS ast_contact_date
                                       FROM db_accounts_last_contacts AS p
                                       GROUP BY p.account_id, follow_up_date, ast_contact_date ");

告诉我进展如何。

附: 我真的建议使用 EntityFramework,因为它将您的视点从 SQL'ish 转换为 C# pov。这通常更容易理解。

【讨论】:

  • 我自己创建了一个视图,但是实体框架现在抱怨“没有主键”你到底如何在视图中设置主键这是我的视图“选择 @987654322 @.account_id AS account_id,p.follow_up_date AS follow_up_date,max(p.last_contact_date) AS last_contact_date,p.idAS @9 987654334@.communique_accounts_last_contacts p group by p.account_id" 另外你不能在上下文中调用 SqlQuery
  • 1st,正如@juharr 在对您的问题的评论中所说,首先您必须在 Group By 子句中有 follow_up_date。 SELECT 中的任何元素都必须分组。第二,不在表中设置主键是一个坏习惯。 3、为了强制实体框架使用列作为主键,使用ISNULL。
  • 好吧,我已经用视图解决了我的问题,上面确实有效,所以我会勾选它,但是我使用视图的原因是,我以前没有使用过视图,所以感觉很好:)
猜你喜欢
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多