【问题标题】:Cannot be resolved into a valid type or function无法解析为有效的类型或函数
【发布时间】:2019-07-10 21:20:19
【问题描述】:

我正在尝试为 sql 数据库中的表值函数构建 OData 端点。我的路由和控制器是正确的,但是我得到了错误

'DataAccessFunctionEntities.GetConfiguration' ---> DataAccess.. is where I built a model
 cannot be resolved into a valid type or function.

虽然获取配置功能在我的控制器中。

我已经尝试调试并得到同样的错误。我找不到有关如何解决此错误的信息。

谢谢

调用 DB 函数(在 Controller 内)给出错误:DB 函数:

[DbFunction("DataAccessFunctionEntities", "GetConfiguration")]
public virtual IQueryable<GetConfiguration_Result> GetConfiguration(string partialPIDs)
{
    var partialPIDsParameter = partialPIDs != null ?
        new ObjectParameter("PartialPIDs", partialPIDs) :
        new ObjectParameter("PartialPIDs", typeof(string));

    return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<GetConfiguration_Result>("[DataAccessFunctionEntities].[GetConfiguration](@PartialPIDs)", partialPIDsParameter);
} 

路由将请求定向到正确的功能。这是控制器功能:

        [HttpGet,EnableQuery]
        public IHttpActionResult GetConfiguration(ODataQueryOptions<GetConfiguration_Result> options)
        {
            string errorType = string.Empty;
            string exServerName = string.Empty;
            int exErrorNumber = 0;
            string exErrorMessage = string.Empty;
            string exStackTrace = string.Empty;
            var inputparameter = "NONE";

            if (options == null)
                throw new ArgumentNullException("options");

            var uri = options.Request.RequestUri.ToString();
            //Decode url for Page-2 and beyond            
            if (uri.Contains("%"))
            {
                uri = Uri.UnescapeDataString(uri);
            }
            var firstOpenParenthesisIndex = uri.Substring(uri.IndexOf("(", StringComparison.OrdinalIgnoreCase) + 1);
            var equalsOperatorIndex = firstOpenParenthesisIndex.Substring(firstOpenParenthesisIndex.IndexOf("=", StringComparison.OrdinalIgnoreCase) + 1);
            var partialPIds = equalsOperatorIndex.Substring(0, equalsOperatorIndex.IndexOf(")", StringComparison.OrdinalIgnoreCase));
            inputparameter = partialPIds;
            var validationResponse = ProcessInput.ValidatePartialPID(partialPIds);
            // Intial Request Logging
            var requestLog = new RequestLog
            {
                Source = "Configuration-GET",
                RequestUrl = options.Request.RequestUri.ToString(),
                UserName = User.Identity.Name,
                StartTime = DateTime.Now,
                EndTime = null,
                RequestStatus = RequestStatus.STARTED.ToString(),
                RequestLength = validationResponse.ParameterCount,
                ResponseLength = 0,
                QueryOptions = ProcessInput.ExtractQueryOptions(options.Request.RequestUri),
                ParentId = null
            };
            var errorlog = new ErrorLog
            {
                RequestLogId = 0,
                ErrorCode = 0,
                ErrorDescription = ""

            };

            if (isLoggingEnabled)
            {
                requestLog.ParentId = _dbLogHelper.LogRequest(requestLog);
            }

            try
            {
                if (validationResponse.IsValidInput == false)
                {
                    requestLog.RequestStatus = RequestStatus.FAIL.ToString();
                    _shortMessage = string.Format(_validationErrorShortMessage, requestLog.Source, validationResponse.InvalidInputMessage, CultureInfo.InvariantCulture);

                    _type = EventLogEntryType.Error;
                    _returnCode = ReturnCodes.ValidationErrorCode;
                    _returnCodeCategory = ReturnCodes.ValidationErrorCode;

                    errorType = "ValidationError";

                    throw new PAIntelODataException(
                        _shortMessage,
                        ODataLogCategory.ValidationException,
                        ReturnCodes.ValidationErrorCode,
                        requestLog.Source);
                }

                partialPIds = validationResponse.XmlPartialPIDs.ToString();

                IQueryable<GetConfiguration_Result> result;
                try
                {
                    result = _DataAccessFunction.GetConfiguration(partialPIds);
                }
                catch (Exception ex)
                {
                    requestLog.RequestStatus = RequestStatus.FAIL.ToString();
                    _type = EventLogEntryType.Error;
                    _returnCode = ReturnCodes.DatabaseErrorCode;
                    _returnCodeCategory = ReturnCodes.DatabaseErrorCode;

                    var innerException = ex;
                    if (ex.InnerException != null)
                    {
                        while (!(innerException is SqlException))
                        {
                            innerException = innerException.InnerException;
                        }
                        var sqlEx = innerException as SqlException;

                        _shortMessage = string.Format(_sqlErrorShortMessage, requestLog.Source, CultureInfo.InvariantCulture);

                        errorType = "SQLError";
                        exServerName = sqlEx.Server;
                        exErrorNumber = sqlEx.Number;
                        exErrorMessage = sqlEx.Message;
                        exStackTrace = sqlEx.StackTrace;

                        throw new PAIntelODataException(
                            _shortMessage,
                            sqlEx,
                            ODataLogCategory.DbException,
                            ReturnCodes.DatabaseErrorCode,
                            sqlEx.Source);
                    }
                    _shortMessage = string.Format(_sqlErrorShortMessage, requestLog.Source, CultureInfo.InvariantCulture);

                    errorType = "SQLGenearalError";
                    exErrorMessage = ex.Message;
                    exStackTrace = ex.StackTrace;

                    throw new PAIntelODataException(
                        _shortMessage,
                        ex,
                        ODataLogCategory.DbException,
                        ReturnCodes.DatabaseErrorCode,
                        requestLog.Source);
                }
                if (result != null)
                {
                    requestLog.RequestStatus = RequestStatus.SUCCESS.ToString();
                    requestLog.ResponseLength = result.ToString().Length;
                    _type = EventLogEntryType.Information;
                    _returnCode = ReturnCodes.Success;
                    _returnCodeCategory = ReturnCodes.Success;
                    errorType = "None";
                    _message = string.Format(_successfulCall, requestLog.Source, CultureInfo.InvariantCulture);
                    return Ok(result, result.GetType());
                }
                return null;
            }

            catch (PAIntelODataException)
            {
                throw;
            }

            finally
            {
                requestLog.EndTime = DateTime.Now;

                //Perform Logging
                //Database Logging:
                if (isLoggingEnabled)
                {
                    var ChildId = _dbLogHelper.LogRequest(requestLog);

                    if (_type == EventLogEntryType.Error)
                    {
                        errorlog.RequestLogId = ChildId;
                        errorlog.ErrorCode = _returnCode;
                        errorlog.ErrorDescription = _shortMessage;
                        _dbLogHelper.LogErrorDetails(errorlog);
                    }
                }

                //EventViewer Logging:
                if (_type == EventLogEntryType.Error)
                {
                    switch (errorType)
                    {
                        case "ValidationError":
                            _message = string.Format(_validationErrorLongMessage, requestLog.Source, requestLog.Source, requestLog.RequestUrl, inputparameter, requestLog.QueryOptions, errorlog.RequestLogId, requestLog.UserName, requestLog.StartTime, requestLog.EndTime, validationResponse.InvalidInputMessage, CultureInfo.InvariantCulture); ;
                            break;
                        case "SQLError":
                            _message = string.Format(_sqlErrorLongMessage, requestLog.Source, exServerName, exErrorNumber, requestLog.Source, requestLog.RequestUrl, inputparameter, requestLog.QueryOptions, errorlog.RequestLogId, requestLog.UserName, requestLog.StartTime, requestLog.EndTime, exErrorMessage, exStackTrace, CultureInfo.InvariantCulture);
                            break;
                        case "SQLGenearalError":
                            _message = string.Format(_sqlErrorLongAbbreviatedMessage, requestLog.Source, requestLog.Source, requestLog.RequestUrl, inputparameter, requestLog.QueryOptions, errorlog.RequestLogId, requestLog.UserName, requestLog.StartTime, requestLog.EndTime, exErrorMessage, exStackTrace, CultureInfo.InvariantCulture);
                            break;
                    }

                    LogHelper.WriteToEventLog(_message, requestLog.Source, _type, _returnCode, _returnCodeCategory);
                }

            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && _AccessModel != null)
            {
                _AccessModel.Dispose();
            }

            if (disposing && _DataAccessFunction != null)
            {
                _DataAccessFunction.Dispose();
            }

            base.Dispose(disposing);
        }

    }
}

【问题讨论】:

  • 您可以显示一些源代码来帮助我们识别问题。
  • 该方法在哪里(以及如何)声明?请不要发布整个源代码,只发布相关部分。
  • @HimBromBeere 我只发布了方法
  • 显然您的方法签名需要ODataQueryOptions&lt;GetConfiguration_Result&gt; 而不是stringpartialIDs 是什么)
  • @HimBromBeere 请再看一次编辑。非常感谢你的帮助。错误来自内部函数的调用..您可以在第一行看到正在构建的模型。

标签: c# sql rest asp.net-web-api odata


【解决方案1】:

我最近遇到了类似的问题。我的 DBContext 是通过使用 EF6 导入数据库模型(数据库优先)生成的。

我认为问题是由于在生成代码后我已将 DBContext 类重命名为我的需要。项目重建成功,但在运行时我得到了完全相同的错误:'MyDataContext.my_fn_name' cannot be resolved into a valid type or function. Near member access expression, line 1, column 23.

我再次重新生成了数据库模型并调整了其他文件中的类名,现在一切正常。

【讨论】:

    【解决方案2】:

    您还记得为结果对象注册复杂类型吗?

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    
        // Add functions on to entity model.
        modelBuilder.Conventions.Add(new FunctionConvention<xxxxxYourEntitiesxxxxx>());
    
        // tvf types
        modelBuilder.ComplexType<GetConfiguration_Result>();
    
    }
    

    并将 ComplexType 属性添加到您的结果类

    [ComplexType]
    public class GetConfiguration_Result
    {
        //..
    }
    

    另外,你的函数声明需要指定命名空间

    [Function(FunctionType.TableValuedFunction, "GetConfiguration", namespaceName : "xxxxxYourEntitiesxxxxx",  Schema = "dbo")]
    public virtual IQueryable<GetConfiguration_Result> GetConfiguration(string partialPIDs)
    

    【讨论】:

    • 我使用您答案的第一部分来解决我的问题。我不需要在类上使用该属性。我在覆盖中使用了流利的断言设置。
    【解决方案3】:

    在我的例子中,我将一个函数从一个 DBContext 对象迁移到另一个,我收到了这个错误'MyDataContext.my_fn_name' cannot be resolved into a valid type or function,因为我错过了这一行

    modelBuilder.Conventions.Add(new FunctionsConvention<MyDataContext>("schemaName"));
    

    OnModelCreating.

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2013-12-14
      • 2015-06-10
      • 2017-02-03
      相关资源
      最近更新 更多