views:

494

answers:

4

Hi, I'm now starting out on DDD, I've already found a nice implementation for ValueObject but I cant seem to find any good implementation for Entities, i want a generic base entity type which will have an ID(needed by the specification) and implement currect equality operations.

Whats the most elegent solution?

+5  A: 

The only characteristic of an Entity is that it has a long-lived and (semi-)permanent identity. You can encapsulate and express that by implementing IEquatable<T>. Here's one way to do it:

public abstract class Entity<TId> : IEquatable<Entity<TId>>
{
    private readonly TId id;

    protected Entity(TId id)
    {
        if (object.Equals(id, default(TId)))
        {
            throw new ArgumentException("The ID cannot be the default value.", "id");
        }

        this.id = id;
    }

    public TId Id
    {
        get { return this.id; }
    }

    public override bool Equals(object obj)
    {
        var entity = obj as Entity<TId>;
        if (entity != null)
        {
            return this.Equals(entity);
        }
        return base.Equals(obj);
    }

    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }

    #region IEquatable<Entity> Members

    public bool Equals(Entity<TId> other)
    {
        if (other == null)
        {
            return false;
        }
        return this.Id.Equals(other.Id);
    }

    #endregion
}
Mark Seemann
+2  A: 

For implementation of correct equality operations I recommend to have a look on a base class of domain entities in Sharparchitecture - http://github.com/codai/Sharp-Architecture/blob/master/src/SharpArch/SharpArch.Core/DomainModel/Entity.cs . It has implementation of all required functionality. And have a look on some other code there, IMO, it will be very useful for you and your case.

zihotki
A: 

I've been using a variation of this as my entity base. Although it is talking about working with NHibernate, I think it covers your requirements for providing an ID and equality operators.

Graham Miller
A: 

I am not sure if you are after a specific library/sample code or guidelines. A good DDD solution will use factory for instantiation, persistency separated from the domain model (most ORM tends to bundle the two together), clearly define domain boundary, enforcing fields and operations through interface.

I would strongly recommend the book Applying DDD and Patterns book by Jimmy Nilson. It discusses in depth about DDD and best practices. The examples are in C# as well which will suit your project.

Fadrian Sudaman