The entity or complex type 'DBModel.User' can not be built in to LINQ to Entities query

1
var result = db.Users.Select(x => new User() {CommpleteName=x.CommpleteName}).FirstOrDefault();

I am trying to select a column from my user table and I receive this error:

  

The entity or complex type 'DBModel.User' can not be constructed in a   LINQ to Entities query.

What is missing from me?

    
asked by okyam 05.07.2016 в 11:59
source

1 answer

0

You can not create a User directly mapped to the Database. If you want to do a new User you must create a UserDTO to do it. I explain:

  • First Create your class DTO :

    public class UserDTO
    {
        public string CommpleteName{ get; set; }
        // Crea las columnas que necesites (mismo nombre que en base de Datos)
    }
    
  • Edit your method so that instead of returning a User it returns a UserDTO :

    var result = db.Users.Select(x => new UserDTO() {CommpleteName=x.CommpleteName}).FirstOrDefault();
    
  • To clarify a bit. If you have in Entity FrameWork your model User with the following fields:

    Id
    Nombre
    Apellido
    CommPleteName
    FechaNacimiento
    

    You create class UserDTO :

    public class UserDTO
    {
        public int Id{ get; set; }
        public string Nombre{ get; set; }
        public string Apellido{ get; set; }
        public string CommpleteName{ get; set; }
        public DateTime? FechaNacimiento{ get; set; }
    }
    

    In this way any query with linq that attacks User what you will do is create the entity UserDTO .

        
    answered by 05.07.2016 / 12:08
    source