2

我已经有一段时间出错了,在阅读她在 SO 上的所有其他帖子时,我没有得到更多的切肉刀。

进行数据库调用时出现错误:

Index (zero based) must be greater than or equal to zero

我有以下方法给我错误:

    public bool IsUserInRole(User user, string roleName)
    {
        using (var repository = new SaxoPublishingEntities())
        {
            repository.Attach(user);

            // THIS CALLS GIVE ME THE ERRROR
            var roles = repository.UserRoles.Include("Users").Where(userRole =>
                userRole.Name == roleName && userRole.Users.Contains(user)).ToList();


            if (roles.Any())
            {
                return true;
            }
            return false;
        }
    }

我的数据库模型:

在此处输入图像描述

我的堆栈跟踪:

[FormatException: Indekset (nulbaseret) skal være større end eller lig med nul og mindre end størrelsen af argumentlisten.]
   System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) +10610374
   System.String.Format(IFormatProvider provider, String format, Object[] args) +63
   System.Data.EntityRes.GetString(String name, Object[] args) +363
   System.Data.Entity.Strings.ELinq_UnsupportedConstant(Object p0) +95
   System.Data.Objects.ELinq.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) +1256
   System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +88
   System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +162
   System.Data.Objects.ELinq.ContainsTranslator.TranslateContains(ExpressionConverter parent, Expression sourceExpression, Expression valueExpression) +136
   System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +1011
   System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +88
   System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +162
   System.Data.Objects.ELinq.BinaryTranslator.TypedTranslate(ExpressionConverter parent, BinaryExpression linq) +122
   System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +88
   System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +162
   System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input) +168
   System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding) +161
   System.Data.Objects.ELinq.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda) +168
   System.Data.Objects.ELinq.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) +66
   System.Data.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) +47
   System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +169
   System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +88
   System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +162
   System.Data.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq) +53
   System.Data.Objects.ELinq.UnarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) +197
   System.Data.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) +47
   System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +169
   System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +88
   System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +162
   System.Data.Objects.ELinq.ExpressionConverter.Convert() +50
   System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) +593
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +255
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +89
   System.Linq.Enumerable.Single(IEnumerable`1 source) +100
   System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3(IEnumerable`1 sequence) +31
   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +56
   System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +97
   System.Linq.Queryable.Any(IQueryable`1 source) +233
   Saxo.Publishing.Business.UserServiceOLD.IsUserInRole(User user, String roleName) in c:\Users\laho\Documents\GitHub\SaxoPublishing\Development\Saxo Publishing\Saxo.Publishing.Business\UserServiceOLD.cs:175
   Saxo.Publishing.Web.Security.UserPrincipal.IsInRole(String role) in c:\Users\laho\Documents\GitHub\SaxoPublishing\Development\Saxo Publishing\Saxo.Publishing.Web\Security\User\UserPrincipal.cs:42
   System.Linq.Enumerable.Any(IEnumerable`1 source, Func`2 predicate) +146
   System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +333
   System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +421
   System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +143
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +978
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +92
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +53
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +538
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +83
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +92
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +531
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +92
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +447
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +49
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +127
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +92
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +388
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

任何想法都非常感谢!:-)

尝试重写版本 1:

public bool IsUserInRole(User user, string roleName)
    {
        using (var repository = new SaxoPublishingEntities())
        {

            var users = repository.Users.Where(c => c.Id == user.Id);

            if (users.Any())
            {
                var myUser = users.First();
                var roles = repository.UserRoles.Where(userRole =>
                    userRole.Name == roleName && userRole.Users.Contains(myUser)).ToList();

                if (roles.Any())
                {
                    return true;
                }
            }
            return false;
        }
    }
4

3 回答 3

4

这是一个众所周知的 EF 限制的神秘信息:您不能在Contains. 而是这样做:

var userId = user.Id;
var roles = repository.UserRoles.Where(userRole => userRole.Name == roleName
                  && userRole.Users.Select(u => u.Id).Contains(userId));
于 2013-01-15T15:39:57.143 回答
0

您是否检查过user.Id不是负数,以及Id两个数据库表中所有行的所有列User并且UserRole从不低于零?

于 2013-01-15T15:07:48.767 回答
0

您发布的方法不是您的错误的来源。查看异常 - 您调用了 aAppendFormat上的某个位置StringBuilder,并且您使用的格式字符串有一个{0}没有相应替换变量的替换标记(即 )。

编辑:查看跟踪:

System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) +10610374
System.String.Format(IFormatProvider provider, String format, Object[] args) +63
System.Data.EntityRes.GetString(String name, Object[] args) +363
System.Data.Entity.Strings.ELinq_UnsupportedConstant(Object p0) +95
System.Data.Objects.ELinq.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) +1256
System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +88
System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +162
System.Data.Objects.ELinq.ContainsTranslator.TranslateContains(ExpressionConverter parent, Expression sourceExpression, Expression valueExpression) +136
System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +1011

这看起来错误源于您正在使用的 Linq-To-Entity 代码提供程序;您正在拉入某种“转换字符串” EntityRes.GetString-我的猜测是格式字符串中有错误。鉴于堆栈跟踪的其余部分,我猜想在您的 LINQ 查询中的某处您指的是一个常量,它不知道如何正确映射 - 可能在 contains 子句中?

在您发布的方法中检查的其他事项:

  • user不为空
  • userRole不为空
  • myUser出现“有效”
  • userRole.Name不为空/空格/空
于 2013-01-15T15:13:52.007 回答