将此SQL查询转换为LINQ查询

时间:2011-08-18 04:36:20

标签: database linq linq-to-sql

我需要将此SQL查询转换为LINQ查询,我还需要公开SQL Select属性:

SELECT Problem.ProblemID, ProblemFactory.ObjectiveID, Objective.Name, ProblemFactory.Time, ProblemType.ProblemTypeName, ProblemFactory.OperationID, 
                     ProblemFactory.Range1ID, ProblemFactory.Range2ID, ProblemFactory.Range3ID, ProblemFactory.Range4ID, 
                     ProblemFactory.MissingNumber
FROM Problem INNER JOIN ProblemFactory ON Problem.ProblemFactoryID = ProblemFactory.ProblemFactoryID
             INNER JOIN ProblemType ON ProblemFactory.ProblemTypeID = ProblemType.ProblemTypeID
             INNER JOIN Objective ON Objective.ObjectiveID = ProblemFactory.ObjectiveID

更新1:

这就是我所拥有的:

        var query = from problem in dc.Problem2s
                    from factory
                    in dc.ProblemFactories
                         .Where(v => v.ProblemFactoryID == problem.ProblemFactoryID)
                         .DefaultIfEmpty()
                    from ...

我正在使用这个例子:What is the syntax for an inner join in LINQ to SQL?

2 个答案:

答案 0 :(得分:3)

这样的东西?

var query =
    from p in ctx.Problem
    join pf in ctx.ProblemFactory on p.ProblemFactoryID equals pf.ProblemFactoryID
    join pt in ctx.ProblemType on pf.ProblemTypeID equals pt.ProblemTypeID
    join o in ctx.Objective on pf.ObjectiveID equals o.ObjectiveID
    select new
    {
        p.ProblemID,
        pf.ObjectiveID,
        o.Name,
        pf.Time,
        pt.ProblemTypeName,
        pf.OperationID, 
        pf.Range1ID,
        pf.Range2ID,
        pf.Range3ID,
        pf.Range4ID, 
        pf.MissingNumber,
    };

但是“SQL Select属性”是什么意思?

答案 1 :(得分:0)

像Linq-to-SQL这样的ORM的一个好处是我们不必将数据展平以从数据库中检索它。如果您在设计器中映射对象(即,如果映射了它们的关系),您应该只能检索Problems,然后根据需要获取它们的关联属性...

var problems = from problem in dc.Problem2s select problem;

foreach (var problem in problems)
{
    // you can work with the problem, its objective, and its problem type.
    problem.DoThings();
    var objective = problem.Objective;
    var type = problem.ProblemType;    
}

因此,您在数据层中保留逻辑数据结构,而不是无法轻易传递的匿名类型。