实体框架代码优先执行标量值函数 [英] Entity Framework Code-First Execute Scalar-Valued Functions

查看:130
本文介绍了实体框架代码优先执行标量值函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何执行使用代码第一个标量函数?下面是我尝试过,但只有查询本身被返回,而不是返回值。

 使用(VAR的DbContext =新FTTRContext())
{

QueryResult中=
dbContext.Database.SqlQuery&所述;串GT(SELECT [DBO] [ufnGetTotalUsers](GETDATE())。)的ToString();
}


解决方案

SqlQuery类返回 DbRawSqlQuery 的一个实例。这个类是一个枚举,它希望你通过任何标准的LINQ运营商,或通过的foreach 等,一一列举它的ToString()此对象上仅仅返回的将被执行的。为了得到你想要的结果,使用。单() .SingleAsync()

  QueryResult中= dbContext.Database 
.SqlQuery<串>(SELECT [DBO] [ufnGetTotalUsers](GETDATE())。)
。单();

这应该返回标量字符串结果你正在寻找。



话虽这么说,您的查询看起来像无效的SQL。你只是想先手从SQL Server的日期?如果是这样,查询也许应该是 SELECT GETDATE()。一旦你这样做,你可能必须使用 .SqlQuery< DateTime的方式>()因为该值的类型不是一个字符串


How can I execute a scalar function using code first? Below is what I have tried but only the query itself is being returned, not the return value.

using (var dbContext = new FTTRContext())
        {

            queryResult =
                dbContext.Database.SqlQuery<string>("SELECT [dbo].[ufnGetTotalUsers] (GETDATE())").ToString();
        }

解决方案

SqlQuery returns an instance of DbRawSqlQuery. This class is an enumerable and it expects you to enumerate it via either the standard LINQ operators, or via foreach, etc. .ToString() on this object simply returns the query that will be executed. To get the result you want, use .Single() or .SingleAsync().

queryResult = dbContext.Database
    .SqlQuery<string>("SELECT [dbo].[ufnGetTotalUsers] (GETDATE())")
    .Single();

This should return the scalar string result you are looking for.

That being said, your query looks like invalid SQL. Are you just trying to just get the date from SQL Server? If so, the query should probably be SELECT GETDATE(). Once you do that, you might have to use .SqlQuery<DateTime>() since the type of that value is not a string.

这篇关于实体框架代码优先执行标量值函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆