使用linq实现内部连接的实体更简洁

时间:2011-11-21 21:54:53

标签: sql linq linq-to-sql linq-to-entities

有什么方法可以减少这种冗长吗?

var model =
(
    from MvrTable in
    LinqEntitiesCtx.Mvrs

    join MvrMedsTable in LinqEntitiesCtx.MvrMeds
    .Where(Id => Id.FKMvrId == 1)//inner join will be fast with this!

    on MvrTable.PKMvrId equals MvrMedsTable.FKMvrId

    join MvrLocationTable in LinqEntitiesCtx.MvrLocations
    on MvrTable.PKMvrId equals MvrLocationTable.FKMvrId

    join MvrEmployeeTable in LinqEntitiesCtx.MvrEmployees
    on MvrTable.PKMvrId equals MvrEmployeeTable.FKMvrId

    //notice i am using a different primary key that previouslly
    join MvrMedsAdminRouteTable in LinqEntitiesCtx.MvrMedsAdminRoutes
    on MvrMedsTable.PKMvrMedsId equals MvrMedsAdminRouteTable.FKMvrMedsId

    select new
    { //here I choose the columns I want to display
       MvrTable.PKMvrId,
       MvrTable.VarianceDescription,
       MvrTable.CaseNumber,
       MvrTable.DateOfReport,
       MvrTable.DateOfVariance
    }
);

上述等效SQL代码:

SELECT [t0].[PKMvrId], [t0].[VarianceDescription], [t0].[CaseNumber], [t0].[DateOfReport], [t0].[DateOfVariance], [t1].[PKMvrMedsId]
FROM [Mvrs] AS [t0]
INNER JOIN [MvrMeds] AS [t1] ON ([t0].[PKMvrId]) = [t1].[FKMvrId]
INNER JOIN [MvrLocations] AS [t2] ON ([t0].[PKMvrId]) = [t2].[FKMvrId]
INNER JOIN [MvrEmployees] AS [t3] ON [t0].[PKMvrId] = [t3].[FKMvrId]
INNER JOIN [MvrMedsAdminRoutes] AS [t4] ON ([t1].[PKMvrMedsId]) = [t4].[FKMvrMedsId]
WHERE [t1].[FKMvrId] =ParamMvrId

2 个答案:

答案 0 :(得分:1)

通过使用Associations,它可能写得更紧凑。像(不完整)的东西:

var model =  from MvrTable in LinqEntitiesCtx.Mvrs
             where MvrTable.MvrMeds.MvrLocations.Any() //These are the Associations
             select new
             {
               MvrTable.PKMvrId,
               MvrTable.VarianceDescription,
               MvrTable.CaseNumber,
               MvrTable.DateOfReport,
               MvrTable.DateOfVariance
             };

由于您没有从这些表中获取任何数据,因此您真的不需要连接。您应该使用Any代替SQL EXISTS

答案 1 :(得分:0)

我相信将join更改为from会更清晰。您也可以缩写您的实体别名

var model =
(
    from MvrTable in LinqEntitiesCtx.Mvrs
    from MvrMedsTable in LinqEntitiesCtx.MvrMeds
                                        .Where(Id => Id.FKMvrId == 1)
                                        .Where(x => MvrTable.PKMvrId == x.FKMvrId)
    from MvrLocationTable in LinqEntitiesCtx.MvrLocations
                                            .Where(x => MvrTable.PKMvrId  == x.FKMvrId)
    from MvrEmployeeTable in LinqEntitiesCtx.MvrEmployees
                                            .Where(x => MvrTable.PKMvrId == x.FKMvrId)  
    from MvrMedsAdminRouteTable in LinqEntitiesCtx.MvrMedsAdminRoutes
                                                  .Where(x => MvrMedsTable.PKMvrMedsId == x.FKMvrMedsId)
    select new
    { 
       MvrTable.PKMvrId,
       MvrTable.VarianceDescription,
       MvrTable.CaseNumber,
       MvrTable.DateOfReport,
       MvrTable.DateOfVariance
    }
);