Home > Enterprise >  How to return a list that contains different types of objects in a controller?
How to return a list that contains different types of objects in a controller?

Time:10-20

I have several tables/models that only have the id-property in common and I have created an interface with only a id-property that all models implements. I am using a controller where I receive an id in a POST-request that I use to search all tables for that id and am returning those rows. There will be at least one match but can also be mor than one match. Right now I am creating a List where I store all matched entries. But when I return the list I only return the id's as the interface only have that property.

Is there some way to return a list of different types where I also get every property from the model ?

CodePudding user response:

You have multiple database tables that have a column that shares an Id and you query all those tables to find any records that have that shared Id. If that's accurate then the following should work:

Start with making C# models for each database table if you've not already done so.

public class MyEverythingModel
{
   public List<Table1> Table1 {get;set;}
   public List<Table2> Table2 {get;set;}
   // additional tables...
}

public class Table1
{
  // Table1 columns
}

public class Table2
{
 // Table2 columns
}

// additional Tables and their columns

Then you can query each table on the column that matches the Id:

var myEverythingModel = new MyEverythingModel 
{
   Table1 = await _context.Table1.Where(x => x.ColumnThatMatchesId == id),
   Table2 = await _context.Table2.Where(x => x.ColumnThatMatchesId == id),
   // additional Tables you need to query
};
  • Related