views:

74

answers:

1

I have a model that looks like this:

public interface IEntity
{
    int Id { get; set; }
}

Then the idea is to have my entities inherit from this interface:

public class User : IEntity
{
    public int Id { get; set; }
}

However, one of my entities actually has a Guid as an identifier.

public class UserSession
{
    public Guid Id { get; set; }
}

I really would like all my entities inheriting from the same interface but that would force me to add an integer based identity column to the UserSession which is unnecessary since Guid is the identity, but it would keep the domain model nice since all entities would inherit from the same base.

What options do I have in this scenario? Can I have two base interfaces, one for int and one for Guid? Should I add an identity column into the UserSession entity although it is unnecessary? I need the Guid so I can't just get rid of it and replace it with and integer.

Any thoughts on best practices?

+1  A: 

You can certainly implement same IEntity interface in all your entities and still have different type in each Id field.

Enter Generics..

define your interface like this.

public interface IEntity<T>
{
    T Id { get; set; }
}

Implementing the interface in your entity..

public class User : IEntity<int>
{
    public int Id { get; set; }
}


public class UserSession : IEntity<Guid>
{
    public Guid Id { get; set; }
}
this. __curious_geek
Very nice! Thanks!
Thomas
How would I implement this on say a repository base interface? It was: public interface IRepository<TEntity> where TEntity : IEntity
Thomas
You have to make a repository generic of TEntity and TEntityKey which is not a very good design choice. Why do you need to have Id field in IEntity?
Szymon Pobiega