传递到字典的模型项的类型为“System.Data.Entity.DynamicProxies.Ob

2019-06-25 20:39发布

没有人知道为什么我收到此错误:

The model item passed into the dictionary is of type
system.Data.Entity.DynamicProxies.Object_3E186F803589BF82895B10E08C
2A9AB68EFA619599418D6EB96585D14874CDC0', 
but this dictionary requires a model item of type 
'System.Collections.Generic.IEnumerable`1[MyApplication.Domain.Entities.Object]'.

这里是我的代码:

控制器:

        public ViewResult Index()
    {
        if (User.Identity.IsAuthenticated)
        {
            MembershipUser currentUser = Membership.GetUser();
            Guid currentUserId = (Guid)currentUser.ProviderUserKey;
            if (currentUser != null && currentUser.ProviderUserKey != null && currentUser.IsApproved)
            {
                Move result = (from move in db.Moves
                         where move.UserId == currentUserId
                         select move).FirstOrDefault();
                return View(result);
            }
        }
        return View(db.Moves.ToList());
    }

视图:

@model IEnumerable<MovinMyStuff.Domain.Entities.Move>
@{
ViewBag.Title = "Index";
}

@foreach (var item in Model)
{
<div id="move-list-item">
    <ul>
        <li>
            <span class="move-name">
                @Html.DisplayFor(modelItem => item.StartCity) 
                @Html.DisplayFor(modelItem => item.StartState)
                @Html.DisplayFor(modelItem => item.StartZip) -
                @Html.DisplayFor(modelItem => item.EndCity) 
                @Html.DisplayFor(modelItem => item.EndState)
                @Html.DisplayFor(modelItem => item.EndZip)
            </span>
        </li>
        <li>@Html.ActionLink("Details", "Details", new { id = item.MoveId }, new { @class = "button" })</li>
    </ul>
</div>
}

Answer 1:

此代码:

Move result = (from move in db.Moves
         where move.UserId == currentUserId
         select move).FirstOrDefault();
return View(result);

试图返回一个结果。 它的抱怨,它希望的结果序列 。 所以,你可以只使用:

var results = (from move in db.Moves
               where move.UserId == currentUserId
               select move).Take(1).ToList();
return View(results);

要么:

Move result = (from move in db.Moves
         where move.UserId == currentUserId
         select move).FirstOrDefault();
return View(new[] { result });

我个人摆脱查询表达式这里,顺便说一句 - 这是使代码比它需要更加复杂。 例如,你可以重写我的第一选择,因为:

var results = db.Moves.Where(move => move.UserId == currentUserId)
                      .Take(1)
                      .ToList();
return View(results);

甚至:

return View(db.Moves.Where(move => move.UserId == currentUserId)
              .Take(1).ToList());


文章来源: The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Object