Can not retrieve data from DB -> ERROR - >The entity or complex type ... cannot be constructed in a LINQ to Entities query

1

I have checked majority of several question but unfortunately, due to lack of enought experience, will not be able to solve this problem without your help.

I can not understand why this error happens. I think code is not wrong.

To see whole code in github

This is

UserController

using BookRental.Models;
using BookRental.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace BookRental.Controllers
{
    public class UserController : Controller
    {

        private ApplicationDbContext db;

        public UserController()
        {
            db = ApplicationDbContext.Create();
        }



        // GET: User/Index
        public ActionResult Index()
        {
            var userList = (from u in db.Users
                       join m in db.MembershipTypes on u.membershipTypeId equals m.membershipTypesIdPK
                       select new UserViewModel
                       {
                           Id = u.Id,
                           fname = u.fname,
                           lname = u.lname,
                           email = u.Email,
                           phone = u.phone,
                           bdate = u.bdate,
                           userMemTypeId = u.membershipTypeId,
                           MembershipTypes = (ICollection<MembershipTypes>)db.MembershipTypes.ToList().Where(n => n.membershipTypesIdPK.Equals(u.membershipTypeId)),
                           disabled = u.disabled

                       }).ToList();

            return View(userList);
        }

UserViewModel

using BookRental.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace BookRental.ViewModel
{
    public class UserViewModel
    {
        [Required]
        public string Id { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        public string email { get; set; }

        [DataType(DataType.Password)]
        public string password { get; set; }

        [DataType(DataType.Password)]
        public string confirmPassword { get; set; }

        public ICollection<MembershipTypes> MembershipTypes { get; set; }

        [Required]
        public int userMemTypeId { get; set; }

        [Required]
        public string fname { get; set; }

        [Required]
        public string lname { get; set; }

        [Required]
        public string phone { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM dd yyyy}")]
        public DateTime bdate { get; set; }

        public bool disabled { get; set; }


    }
}

Index view

    @model IEnumerable<BookRental.ViewModel.UserViewModel>
@using BookRental.Models
    @{
        ViewBag.Title = "Index";
    }

    <h2>Genre</h2>

    @Html.Partial("_CreateButtonPartial")

    <br />
    <br />
    <br />

    <table class="table table-hover">
        <thead class="thead-dark">
            <tr class="row">
                <th class="col">
                    @Html.DisplayNameFor(m => m.fname)
                </th>
                <th class="col">

                    @Html.DisplayNameFor(m => m.lname)
                </th>
                <th class="col">

                    @Html.DisplayNameFor(m => m.email)
                </th>
                <th class="col">

                    @Html.DisplayNameFor(m => m.bdate)
                </th>
                <th class="col">

                    @Html.DisplayNameFor(m => m.phone)
                </th>
                <th class="col">
                    @Html.DisplayNameFor(m => m.disabled)
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr class="row">
                    <td class="col">
                        @Html.DisplayNameFor(item => item.fname)
                    </td>
                    <td class="col">

                        @Html.DisplayNameFor(item => item.lname)
                    </td>
                    <td class="col">

                        @Html.DisplayNameFor(item => item.email)
                    </td>
                    <td class="col">

                        @Html.DisplayNameFor(item => item.bdate)
                    </td>
                    <td class="col">

                        @Html.DisplayNameFor(item => item.phone)
                    </td>
                    <td class="col">
                        @Html.CheckBoxFor(m => item.disabled, new { @class = "disabled" })
                    </td>
                    <td class="col">
                        @Html.Partial("_TableButtonPartial", new IndividualButtonPartial { userId = item.Id})
                    </td>
                </tr>
            }
        </tbody>
    </table>

Error

    System.NotSupportedException
  HResult=0x80131515
  Message=The entity or complex type 'BookRental.Models.UserViewModel' cannot be constructed in a LINQ to Entities query.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

Error Screen

c#
asp.net-mvc
ef-code-first
visual-studio-debugging
asked on Stack Overflow Apr 22, 2020 by Фуад Теймуров • edited Apr 22, 2020 by Фуад Теймуров

1 Answer

1

The problem is explained here; The entity cannot be constructed in a LINQ to Entities query

If you project onto a mapped entity, what you basically do is partially load an entity, which is not a valid state. EF won't have any clue how to e.g. handle an update of such an entity in the future (the default behaviour would be probably overwriting the non-loaded fields with nulls or whatever you'll have in your object)

In your Identitymodels.cs, you're defining the UserViewModel as an Entity Framework entity which is incorrect because you already have a ApplicationUsers entity and from the name itself UsersViewModel, you expect it to be just a View Model.

To fix this, just remove this line from your IdentityModels.cs;

public System.Data.Entity.DbSet<BookRental.ViewModel.UserViewModel> UserViewModels { get; set; }
answered on Stack Overflow Apr 22, 2020 by Jerdine Sabio

User contributions licensed under CC BY-SA 3.0