【问题标题】:How can I convert a MVC sql query to a Linq query?如何将 MVC sql 查询转换为 Linq 查询?
【发布时间】:2015-10-15 15:30:36
【问题描述】:

我是 MVC 的新手。 Linq 是在数据库中进行查询的系统。但我现在在使用 Linq 时遇到了困难。有人知道如何将我的 sql 语句转换为 Linq 吗?

我的实体,单独的上下文

localDB.summaries

accountDB.account


SELECT * FROM summary 
WHERE studentID = 
(SELECT studentID FROM accounts WHERE username = 'username123')

FROM user IN localDB.summaries
WHERE -------- please guide my linq--------
SELECT user

【问题讨论】:

  • 另外,你也可以使用 linq lambda 表达式:localDB.summaries.Where(x => localDB.accounts.Any(y => y.studentID == x.studentID && y.username == "username123"));

标签: sql asp.net-mvc linq


【解决方案1】:

在不知道你的实体的情况下猜测:

var query = from user in localDB.summaries
join account in localDB.accounts on user.studentID equals account.studentID
where account.username == "username123"
select user;

【讨论】:

  • 这是不同的上下文。用于摘要的 localDB 和用于用户名的 accountDB 有错误:System.NotSupportedException:指定的 LINQ 表达式包含对与不同上下文关联的查询的引用。
  • 您从未在问题中指定这一点
  • 先生,我很抱歉。我现在编辑了细节并添加了它。
  • 你的sql暗示表在同一个数据库中?
【解决方案2】:

我假设帐户表已根据学生 ID 与学生映射我的意思是存在外键关系,因此假设:

var data = localDB.summaries.where(c=>c.Students.Account.FirstorDefault().username == "username123")

【讨论】:

  • 我在我的问题中添加了一些信息。我必须上下文。用于摘要的 localDB 和用于帐户的 accountDB。
猜你喜欢
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多