Converting Datetime to string inside a viewModel object when consulting sql server

0

I have an exception when I try to covert a date that I bring from sql server to string type inside a viewModel object.

It says the following: System.NotSupportedException: 'LINQ to Entities does not recognize the method' System.String Format (System.String, System.Object) 'of the method, and this method can not be converted into a storage expression. '

    
asked by Steven Giraldo 04.10.2018 в 05:07
source

1 answer

0

Even before you call the .ToList() of your query all that code will try to move to SQL statement, for which some functions like you have in the exception could not be translated into SQL, so here you have two options:

  • To your query you can add .Tolist() after Where . With this you would have the objects in memory and the .Select could apply the format that you are indicating without problems. It should be noted that in ToList() , you would only be bringing the entities of ActividadesUser and as in select you need data of Usuario and Actividades , it is necessary that addition .Include( to include the relationships of the entities Daughters . Your query would be this way for example:
  • db.ActividadesUser
    .Include(x => x.User)
    .Include(x => x.Actividades)
    .Where(x => x.UserId == usuario)
    .ToList()
    .Select(x => new ActividadesViewModel
    {
    UsuarioId = x.User.Email,
    Actividad = x.Actividades.Actividad,
    Descripcion = x.Actividades.Descripcion,
    Fecha = string.Format("{0:ddd (MMMM yyyy)}", x.Actividades.Fecha)
    }).ToList()
    
  • Do not apply the format in the .Select( , work with the type datetime instead of string and format it in your view.
  • Greetings, I hope you serve

        
    answered by 04.10.2018 / 08:44
    source