How to simulate Derived table with linq to Entitie

2019-09-09 11:31发布

问题:

How I can simulate Derived Table with linq?

Consider this Code:

SELECT * FROM (SELECT * FROM Mytbl) AS tmp WHERE tmp.ID=1

How I can write this with Linq ?

thanks

EDIT 1:

How to convert this to linq?:

select 
convert( decimal(10,1), ROUND(A.c2*100,8)),
convert( decimal(10,1), ROUND(A.c3*100,8))
from
(
SELECT 
    (
        SELECT CONVERT(INT, COUNT(ID))
        FROM tbl
        WHERE (col06 >= @param_Min and col06 <= @param_Max )

    )
    /  
    (
        SELECT CONVERT(INT, COUNT(ID))
        FROM tbl
        WHERE (col06 >= 10 )                    
    ) as c2
    (
        SELECT CONVERT(INT, COUNT(ID))
        FROM tbl
        WHERE (col06 >= @param_Min and col06 <= @param_Max )
            AND (col03 = 1)
    )
    /  
    (
        SELECT CONVERT(INT, COUNT(ID))
        FROM tbl
        WHERE (col06 >= 10 ) AND (col03 = 1)    
    ) as c3
) AS A

回答1:

  1. **SELECT * FROM (SELECT * FROM Mytbl) AS tmp WHERE tmp.ID=1**

Linq version

var result = db.MyTbl.Where( x => x.ID == 1);

2.

 var query = 
                let c1= from b in db.MyTbl
                                  where b.col06 >= @param_Min//some condition
                                  select b.ID
                let c2= from b in db.MyTbl
                                  where b.col06 >= 10//some condition
                                  select b.ID
                let c3=from b in db.MyTbl
                                   where b.col06 >= @param_Min//some condition
                                  select b.ID

                select new
                { 
                    c2.ID,//perform Round and other operation on this  
                    c3.ID//perform Round and other operation on this 

                };


回答2:

WITH(NOLOCK) is not possible to achieve in LINQ-to-Entities so you should just wrap it in stored procedure and call it.

Generally this is computation and not data set retrieval so it's not very suitable for Linq-to-entities. When using EF computation should be done in your application so you should call four sub queries separately and calculate the result in your application. As alternative you can use stored procedure.