用于替换此LINQ语句的优化存储过程

时间:2011-02-26 19:30:51

标签: sql-server database stored-procedures c#-4.0 linq-to-entities

我在SQL Server 2008中有以下两个表

TABLE [JobUnit](
    [idJobUnit] [int] IDENTITY(1,1) NOT NULL,
    [Job_idJob] [int] NOT NULL,  // Foreign key here
    [UnitStatus] [tinyint] NOT NULL, // can be (0 for unprocessed, 1 for processing, 2 for processed)   
    )

TABLE [Job](
    [idJob] [int] IDENTITY(1,1) NOT NULL,
    [JobName] [varchar(50)] NOT NULL,   
    )

工作:JobUnit是一对多的关系

我正在尝试编写一个有效的存储过程来替换以下LINQ语句

public enum UnitStatus{
    unprocessed,
    processing,
    processed,
}

int jobId = 10;

using(EntityFramework context = new EntityFramework())
{
    if (context.JobUnits.Where(ju => ju.Job_idJob == jobId)
        .Any(ju => ju.UnitStatus == (byte)UnitStatus.unproccessed))
    {
        // Some JobUnit is unprocessed
        return 1;
    }
    else
    {
        // There is no unprocessed JobUnit
        if (context.JobUnits.Where(ju => ju.Job_idJob == jobId) //
            .Any(ju => ju.UnitStatus == (byte)UnitStatus.processing))
        {                   
            // JobUnit has some unit that is processing, but none is unprocessed 
            return 2;
        }
        else
        {
            // Every JoUnit is processed
            return 3;
        }
    }
}

感谢您阅读

1 个答案:

答案 0 :(得分:1)

实际上,你只是在寻找特定工作中所有单位的最低状态?

CREATE PROCEDURE GetJobState @jobId int AS
SELECT MIN(UnitStatus)
FROM JobUnit 
WHERE Job_idJob = @jobId

我还应该说你可以在Linq中轻松使用这种方法。