Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a novice in both ASP.NET MVC and Linq to Entity. I am developing an application that has 4 business layers: UI, Business logic, DAL and service layer. I have written a test logic but it is giving me the following error:
**The Entity Or Complex Type Cannot Be Constructed In A Linq To Entities Query.**

**LInq to Entity query in DAL(named Repositories):**
C#
public List<PROGNOSI> GetData(int id)
        {
            using (CAAEntities context = new CAAEntities())
            {
                var query = from p in context.PROGNOSIs
                where p.ID == id
                select new {ID = p.ID, NAME = p.NAME };

                var data = query.ToList().Select(r => new PROGNOSI
                {
                     ID = r.ID, NAME= r.NAME
                }).ToList();

                return data;

            }
}

Then I am using the above method in controller function in UI(CAA_AuditPlanning) layer as:

C#
public ActionResult Prognosi()
        {
           var aeromedicalRepository = new AeroMedicalRepository();
           List<PROGNOSI> data = aeromedicalRepository.GetData(1); //here the error comes

           return View(data);

        }

**View:**
HTML
@model  IEnumerable<Repositories.PROGNOSI>

<div class="col-lg-8">
        <table class="Reports-filter">
@foreach (var item in Model)
                {

            <tr>
                <td>@Html.DisplayFor(m => item.NAME)</td>
            </tr>
}
        </table>
    </div>

**Model Class:**
C#
public class Prognosi
{
    public string ID { get; set; }

    [Required]
    [Display(Name = "Prognosis Title")]
    [StringLength(150, ErrorMessage = "Title cannot be longer than 150 characters.")]
    public string NAME { get; set; }

}

Can anyone tell me what is wrong with my code?

Note: If I do not use Repositories Layer and write GetData logic directly in controller function then code works fine. Apparently, the problem arises in passing method results.
Posted
Updated 24-May-15 6:39am
v3

1 solution

This error message means that you can't return result of query as mapped entity. You have to return anonymous type.

Try to simplify GetData function as follow:

C#
using (CAAEntities context = new CAAEntities())
{
    var query = context.PROGNOSIs
        .Where(p=>p.ID == id)
        .Select(p=>new{ID = p.ID, NAME = p.NAME})
        .ToList();

    return query;
}


For further information, please see:
Error: The entity or complex type cannot be constructed in a LINQ to Entities query
The entity or complex type ' ' cannot be constructed in a LINQ to Entities query [duplicate]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900