Home > Mobile >  Ef core 2 diferent tables to same dto
Ef core 2 diferent tables to same dto

Time:03-18

I'm doing a select to an IQueryable, so this IQueryable can come from 2 different tables but the dto is the same. My problem is that I'm duplicating the code because of the select for each of them. Is there any way to create a general method that receives the IQueryable and inside it does the select?

CodePudding user response:

You have an interface:

interface INamed{
  string Name {get; set;}
}

You have two different table entities that implement it because they both have a Name property:

public class Person : INamed {
  public string Name { get; set; }
}
public class Company: INamed {
  public string Name { get; set; }
}

You have a mapping method that takes anything that implements an INamed and kicks out an object with the Name set:

SomeDto Map(INamed x){
  return new SomeDto { Name = x.Name }
}

And you call it appropriately:

context.Persons.Select(person => Map(person) );

context.Companies.Select(company => Map(company) );
  • Related