4

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?

Thomas
  • 5,888
  • 7
  • 44
  • 83

3 Answers3

3

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
  • 42,787
  • 22
  • 113
  • 137
  • How would I implement this on say a repository base interface? It was: public interface IRepository where TEntity : IEntity – Thomas May 03 '10 at 18:48
  • 2
    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 May 04 '10 at 12:52
1

Try this

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

public abstract class BaseEntity<T, U>
{
    U _id;
    public U Id
    {
        get { return _id; }
        set { _id = value; }
    }
}

And then

public class Person : BaseEntity<Person,int>
{
    string _firstName;
    string _lastName;

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }
} 

or

public class City: BaseEntity<City,Guid>
{
    string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

}       
Mirza
  • 323
  • 4
  • 13
0

Always use a Guid to identify an entity.

Guids have significant advantages over ints in that they can be generated on the client, which frees you up to batch up commands, display the result of an insert in AJAX without querying for the ID, etc.

Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148