Convert DbSetT to different data type in EF - Linq

1

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!

    
asked by Juan Salvador Portugal 27.06.2018 в 14:29
source

2 answers

1

In Stackoverflow in English a Tim Schmelter answered my question , I translate your answer so you can be useful to other people.

  

You can not do it, since it only supports constructors without parameters,   but you can do it with Linq-To-Objects , which can be forced with    AsEnumerable

Obj2 objeto = db.Obj1
   .Where(x => x.id == "0")
   .AsEnumerable()   // <--- here
   .Select(x => new Obj2(x))
   .FirstOrDefault();
     

Therefore, the Where will be executed in the database, but the   rest, will be executed with Linq-To-Objects

     

For more information, you can see this post in the Jon's blog   Skeet

    
answered by 27.06.2018 / 15:04
source
0

It is not necessary to execute Where and then FirstOrDefault to obtain the first element through the collection

For that, execute FirstOrDefault and pass the condition in this method directly

Obj2 objeto = db.Obj1.FirstOrDefault(x => x.id == "0").Select(x => new Obj2(x));

Greetings

    
answered by 27.06.2018 в 15:09