I have a WCF service which works with SQL through EntityFramework via net.tcp
Its allowed to clients to query items by Id from Db.
I have a plenty of methods which looks like this:
public SiteDTO GetSiteById(long siteId)
{
using (var context = new MyDbContext())
{
var site = context.Site.Find(siteId);
return AutoMapper.Mapper.Map<SiteDTO>(site);
}
}
so I decided to make The One Method to rule them all:
public TDTO GetEntityById<TDTO, TSet>(object id)
where TDTO : class
where TSet : class
{
using (var context = new MyDbContext())
{
var entity = context.Set<TSet>().Find(id);
if (entity == null)
return default(TDTO);
return AutoMapper.Mapper.Map<TSet, TDTO>(entity);
}
}
but the problem is that the client which should use it know nothing about TSet
type (its a database type and clients only works with DTOs), so this method cannot be called that way. I need to make it like that:
public TDTO GetEntityById<TDTO>(object id)
where TDTO : class
{
using (var context = new MyDbContext())
{
//Something like this and a lot of reflection...
Type setType = Resolver(typeof(TDTO));
//I know this won't work. Just to show my intentions
var entity = context.Set<setType>().Find(id);
if (entity == null)
return default(TDTO);
return AutoMapper.Mapper.Map<setType, TDTO>(entity);
}
}
I know how to solve the problem robust way - make Dictionary<Type,Type>
register it one time and use it.
Question: Is there more elegance way (maybe with AutoMapper methods) to do it?