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?
Asked
Active
Viewed 417 times
0
-
That is what an interface is used for. Your select is an interface into the class object. – jdweng Mar 16 '22 at 12:06
-
You take that code, put it in a method, make an interface that specifies all those props on the *table* entity, make each different entity implement that interface, and then your method can take an object of type IWhatever – Caius Jard Mar 16 '22 at 12:07
-
What about using an `IQueryable` extension method? – WBuck Mar 16 '22 at 12:07
1 Answers
1
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) );

Caius Jard
- 72,509
- 5
- 49
- 80
-
Note; objects have been simplified for clarity of demonstrating the point – Caius Jard Mar 16 '22 at 12:13