简体   繁体   中英

Help Translating SQL to LINQ-to-Entities

Well, I think trying to understand someone elses SQL can be trying enough but trying to convert said SQL to Entity Framework is another level of pain...

I have this SQL:

SELECT 
    MAX(IntegerColumn) - MIN(IntegerColumn) 
    / 
    DateDiff(day, MIN(DateColumn) , MAX(DateColumn)) 
    * 
    DateDiff(day, MAX(DateColumn) , @TargetDate) 
    + 
    MAX(IntegerColumn) 
    AS Calculation      
FROM MyTable 
WHERE TargetId = @TargetId

Forgetting operator precedence, so far, I have come up with the following LINQ to Entities, which I am regarding with extreme suspicion:

var calculation = 
    (from f in this.ObjectContext.MyTable 
        where f.TargetId == targetId
        group f by f.IntegerColumn into o
        let maxIntegerColumn = o.Max(x => x.IntegerColumn)
        let minIntegerColumn = o.Min(x => x.IntegerColumn)
        let maxDate = (from t in o select t.DateColumn).Max()
        let minDate = (from t in o select t.DateColumn).Min()
        select new
        {
            Result = (maxIntegerColumn - minIntegerColumn) /
            ((SqlFunctions.DateDiff("day", minDate, maxDate) *
            SqlFunctions.DateDiff("day", maxDate, targetDate)) + maxIntegerColumn)
        }).FirstOrDefault();

if (calculation != null)
{
    if (calculation.Result != null)
    {
        return calculation.Result.ToString();
    }
}

That just looks wrong, wrong, wrong and is the result of blindly following too many blog posts.

Is this in the right direction? How can I simplify what's going on?

If it works, go with it. You can reformat and refactor your LINQ to make it look prettier but it appears as though it's doing the right thing.

In this case, I'd probably write a stored procedure - you're performing awkward calculations that need to be done in the database, so just write them in the database and then execute them from your code.

You could run the LINQ query and observe the sql generated (via Sql Server Profiler or any 3rd party profiler) and decide if it generates the exact sql or at least what you need.

If I were in your shoes i'd probably create a stored procedure that accepts the 2 values as parameters and call that from entity framework. The linq query is not really readable ... :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM