使用LINQ从SQL存储过程返回单个值

时间:2018-10-29 13:50:31

标签: c# linq

我有一个存储过程,该过程返回要使用LINQ返回的十进制值。我使用以下代码通过ViewModel返回多个值,但是从不返回单个值,并且老实地在网上寻找东西:

var CompanyIdParameter = new SqlParameter("CompanyId", companyId);
departmentListVM = db.Database.SqlQuery<DepartmentViewModel>("sp_SELECT_Department_Hierarchy @CompanyId", CompanyIdParameter)
    .Select(x=> new DepartmentViewModel()
    {
        pkiDepartmentId = x.pkiDepartmentId,
        DepartmentName = x.DepartmentName,
        ParentDepartmentId = x.ParentDepartmentId,
        ParentDepartmentName = x.ParentDepartmentName,
        fkiCompanyId = x.fkiCompanyId,
        isLastDept = x.isLastDept
    }).ToList();

我不能做这样的事情吗?

var IdeaIdParameter = new SqlParameter("IdeaId", ideaId);
var SessionIdParameter = new SqlParameter("SessionId", sessionId);
var CriteriaIdParameter = new SqlParameter("CriteriaId", item.fkiJudgingCriteriaId);
decimal result = db.Database.SqlQuery<decimal>("sp_SELECT_Department_Hierarchy @IdeaId, @SessionId, @CriteriaId", IdeaIdParameter, SessionIdParameter, CriteriaIdParameter)
                        .Select(x => x.value);

我会让它变得太复杂还是有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

怎么样

var value = db.Database.SqlQuery<decimal>("sp_SELECT_Department_Hierarchy @IdeaId, @SessionId, @CriteriaId", IdeaIdParameter, SessionIdParameter, CriteriaIdParameter)
                  .SingleOrDefault();