I'm working on an expression Linq
in which I get an object of DBContext
, and I want to convert it into an object of ViewModel
My ViewModel
receives as parameter an object obtained from DBContext
to work the information and return it completely
public class Obj1 // Objeto obtenido de la base de datos
{
public int id { get; set; }
public string Param { get; set; }
public string Param2 { get; set; }
public string Random { get; set; }
}
public class Obj2 //ViewModel
{
public string ParamFormateado { get; set; }
public string Random { get; set; }
public Obj2(Obj1 parametro)
{
ParamFormateado = parametro.Param + parametro.Param2;
Random = parametro.Random;
}
}
In essence, the second class works on the parameters of the first and formats them and then moves to a view.
What I'm trying to do is get a Obj2
from a base from a DBContext
that has Obj1
I try something like this
Obj2 objeto = db.Obj1.Where(x => x.id == "0").Select(x => new Obj2(x)).FirstOrDefault();
Is it possible to make a query Linq
similar to the one I am proposing? since otherwise, I end up having expressions Linq
extremely long to format this information, but what would be the best alternative in these cases?
Greetings and thanks for taking the time to read!