0

Im using EF 6 and I need a LINQ query to fetch all the data to my ViewModel. Every Event has a status (one to one) There are not FK in tables

I want do display something like that:

EventID   EventStatusID   Name      EventDate   EventDesc    
99        1               Allowed   2000-1-1    Music festival

ViewModel class:

public class EventVM : Event
{
    public EventStatus EStatus { get; set; }
}

Event class:

[Serializable]
public class Event
{
    public int EventID { get; set; }
    public int EventStatusID { get; set; }
    public string EventNumber { get; set; }
    public DateTime EventDate { get; set; }
    public string EventDesc { get; set; }
}

Event status class:

[Serializable]
public class EventStatus
{
    public int EventStatusID { get; set; }
    public string Name{ get; set; }
    public string Desc{ get; set; }
}

Event table:

dbo.Event

    Column name     Type       Allow nulls
PK  Eventid         int        no
    Eventstatusid   int        no
    Eventnumber     nvarchar   no
    Eventdate       date       no
    Eventdesc       nvarchar   no

EventStatus table:

dbo.EventStatus

    Column name     Type       Allow nulls
PK  Eventstatusid   int        no
    Desc            nvarchar   no
    Name            nvarchar   no

I stucked in this moment :

            var viewModel =
           (from ev in db.Events
            join evs in db.EventStatus on ev.EventStatusID equals evs.EventStatusID
            where ev.EventStatusID == id

            select new EventVM
            {
                EventID = ev.EventID
            }).First();

with error:

System.NotSupportedException: 'The entity or complex type 'ModelEvent.EntityFramework.Concrete.EventVM' cannot be constructed in a LINQ to Entities query.'

I cant change View Model, i have to use this one

żółw
  • 11
  • 3

1 Answers1

0

You need to create model or use anonymous type to gather data from DB (don't forget to use ToList() to actually gather data), and then map it's properties to properties of a EventVM. You are getting this error, because EF is unable to properly create instance of EventVM.

Pavel Pája Halbich
  • 1,404
  • 2
  • 17
  • 20