【问题标题】:What is the Linq Query of the following SQL以下SQL的Linq Query是什么
【发布时间】:2014-01-23 12:06:27
【问题描述】:

我是 nHibernate 的新手。我有以下 SQL 内连接查询,

SELECT e.name, 
       d.deptname 
FROM   demo_employee AS e 
       INNER JOIN demo_department AS d 
               ON e.departmentid = d.deptid 

下面的sql查询使用Query Over的linq表达式是什么。

我已经编写了以下查询,但它在以下位置“c.Department.DeptId”处出现错误。

 var Query =
    Session.QueryOver<Employee>()
        .JoinQueryOver<Department>(c => c.Department.DeptId)
            .Where(k => k.Name == k.DeptId);

【问题讨论】:

  • 这应该是相当简单的,但如果你先尝试自己解决它,你会学到更多:你尝试了什么,发生了什么?请使用您已经尝试过的 LINQ 查询以及收到的任何错误等更新您的问题。
  • @Undefiend 无需更新。你的问题被搁置了。下次尝试提出更好的问题
  • @SubinJacob:不,搁置问题的目的是可以编辑和改进它们,然后重新打开。当这个问题可以挽救时,OP 不需要提出 新的 问题。
  • 我已经更新了我的问题
  • ...在重新打开您的问题之前,您尝试过的查询将不起作用。 ORM 世界的工作方式有点不同。你确实必须表达JOIN。这是由您的映射完成的。所以只需使用:.JoinQueryOver&lt;Department&gt;(c =&gt; c.Department) 让两个表都加入。电话Where() 说:Department.Name == Department.DeptId... 这很可能不是您想要的

标签: sql linq nhibernate


【解决方案1】:

这是QueryOver 版本。

我们正在使用别名,即:声明 null 引用 Employee employee = null 用于对所有属性进行全类型访问。 NHibernate 表达式解析器稍后会根据映射将它们转换为字符串(列名)。

我们还可以获得对 QueryOver 的 FROM 部分的引用。 query代表Employee,joined query代表Department(depQuery),我们可以直接过滤。

最后我们可以使用 List() 来获取 (SELECT) 所有映射的属性,或者做一些投影:.Select().SelectList()。通过投影,我们应该使用一些 DTO。

// aliasing, see the Projections of the SELECT clause
Employee employee = null;
Department department = null;

// the Employee query, with alias
var query = session.QueryOver<Employee>(() => employee);

// this way we can have reference to department query, if needed
var depQuery = query.JoinQueryOver<Department>(() => employee.Department, () => department);

// WHERE
// filtering the Employee
query.Where(e => e.Name == "Undefined");

// the department filtering
depQuery.Where(d => d.DeptName == "Management");


// paging, if needed
query.Skip(100);
query.Take(10);

1) 选择所有属性

var list = query.List<Employee>();

var employeeName = list.ElementAt(0).Name;
var departmentName = list.ElementAt(0).Department.DeptName; 

2) 投影

// The DTO class to be projected into
public class MyDTO
{
    public virtual string EmployeeName { get; set; }
    public virtual string DepartmentName { get; set; }
}


// Select with projection of just two columns
MyDTO dto = null;

// SELECT
// projection, explicit property/column to be selected only
query.SelectList(l => l
    // the full power of aliasing
    .Select(() => employee.Name).WithAlias(() => dto.EmployeeName)
    .Select(() => department.DeptName).WithAlias(() => dto.DepartmentName)
    );

var list = query
    .TransformUsing(Transformers.AliasToBean<MyDTO>())
    .List<MyDTO>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2016-10-15
    相关资源
    最近更新 更多