Should Entities/DTOs implement Interfaces?

Coordinator
Nov 27, 2012 at 9:03 PM

User @juliochristo has suggested the following:

I would really like to see interfaces.

Currently, it is difficult to create a generic method to Get a DTO by ID from the repository.  See this work in progress function call below:

// eventually this can become an extension method
public EntityType GetDTOByID<EntityType>(MyEntities entities, string keyName, int id) where EntityType : class
{
    var q = entities.CreateObjectSet<EntityType>().Where(string.format("it.{0} = @tableNameId", keyName));  // may need to use '?' instead of tags
    q.Parameters.Add(new ObjectParameter("tableNameId", id));
    var entity = q.Single();
    if (entity == null)
        return null;
    else
        return entity.ToDTO();  // cannot do this because we don't know what methods "EntityType" supports!!
}

Here is another example:

public DTOType GetDTOByPrimaryKey<EntityType, DTOType>(ExtendedATPEntities entities, int id) where EntityType : EntityObject where DTOType: IDTO //it would be really nice if we could do something like this
{
    EntityType entity = GetByPrimaryKey<EntityType>(entities, id);
    if (entity == null)
        return null;
    else
        return entity.ToDTO();  // compile time error.
}

Coordinator
Nov 27, 2012 at 9:06 PM

Hello @juliochristo, thanks for your suggestion.

I can see the power of what you want.

So the Interfaces should be one to implement in each entity and another interface to implement in each DTO.

How would you suggest to call these 2 interfaces? IEntityToDTO and IDTOToEntity? IEntity(something)... and IDto or IDTO...

Nov 29, 2012 at 8:23 PM

Yes this is precisely what I am looking for!!

It should be relatively straightforwards I think.  The  most interesting bit here is extended the generated EF entities (partial class) so that they inherit the common interface.  I'm not sure how that will play into your current architecture with the assemblers however. 

Coordinator
Nov 29, 2012 at 10:25 PM

Assemblers won't be a problem.

I think that this should be a optionally so the user can decide to include or not the use of interfaces. Cases could exists where this is not needed and the developer could choose to not use them so no more complexity is added to the solution.

Here is the work item I created.

Thanks a lot for your interest!

Marked as answer by ffernandez on 12/30/2013 at 6:54 PM