Home > Software design >  how to transfer whole of row into model in linq without putting name of every attribute in {}
how to transfer whole of row into model in linq without putting name of every attribute in {}

Time:07-06

I have this model

public class model 
{
public string at1{set; get;}
public string at2{set; get;}
public string at2{set; get;}
public string at2{set; get;}
public string at2{set; get;}
};

I make an instance of model like:

List<model> md= new List<model>();

then I write a query like this from a table with same names as model is

md = db.SomeTable.Where(a => a.at1 == '1').Select (row => new model()).ToList()

What I am seeking is put whole of any row in SomeTable into model's format. Obviously my code isn't working and return null data and if change it like this, it works

md = db.SomeTable.Where(a => a.at1 == '1').Select (row => new model
{ 
at1=a.at1,
at2=a.at2,
at3=a.at3,
at4=a.at4,
at5=a.at5,
).ToList()

I dont want to put every attribute name in my query, Is there any substitute?

Note: I dont want to use Model of Database I mean (SomeTable's Model) I want to receive result of query in another model. (Because of join, include, etc)

CodePudding user response:

I cant comment yet so posting as an answer.

1 on using @MindSwipe's Automapper if you can. Where I work we use Automapper to take the information from an api response object and map it to the view model properties. Super easy to use if your objects are similar in structure. You can also extend it for more complicated structures.

I've also come across practices in Dart/Flutter where Classes have a map function where you can pass a json string for eg and it maps the relevant information across.

(NOT RECOMMENDED!!)This option might also leave you vulnerable to potential runtime issues etc. The final option I can think of is to use something like Reflection to create a generic function where you have to go through the properties between class A and class B and if the names match then set the value. That said I have a feeling Automapper might be doing this/something similar under the hood, so why reinvent the wheel I guess.

  • Related