Related Articles:
A Different Kind of Entity Framework (this article)
Entities Live in Repositories
Before I can get into some of the Machine Learning and Event Sourcing topics I want to discuss I need to establish an Entity Model.
This is not an ORM. While those certainly have their place, and features like code-first in modern frameworks are expanding the number of places where they are appropriate, there are still many places I prefer to use something a little more rustic: hand-coded SQL for example.
If you haven’t read it already, I highly recommend the DDD bible:
There are a lot of reasons why you might choose to use or not use an ORM, for me performance is often a huge concern. You may simply need features not offered my your ORM of choice: specific kinds of change tracking, serialization, UI bindability, inability to use the base classes required by an ORM, specific cache strategy needs, or for other reasons.
Starting with Simple Entities
We’ll start by defining a simple interface and implementation of an Entity. An Entity is an object (representing data) whose lifetime is defined by some kind of Key or Id. Keys will often be a primitive or struct.
/// <summary>
/// An Entity has a key(Id) representing its identity. Implementors should consider overriding Equals and GetHashCode
/// in terms of this key
/// </summary>
public interface IEntity
{
/// <summary>
/// Return the Id
/// </summary>
/// <returns></returns>
object GetId();
/// <summary>
/// Set the id
/// </summary>
/// <param name="value">New Id value</param>
void SetId(object value);
}
Since we’re programming in C#, it would be a crime not to provide a generic version:
/// <summary>
/// An Entity with a typed key
/// </summary>
/// <typeparam name="TId">The id type, often a value type</typeparam>
public interface IEntity<TId> : IEntity
{
/// <summary>
/// The Entity Id of the given instance. Should be implemented in terms of Get/SetKey()
/// </summary>
TId Id { get; set; }
}
Next Steps
You would be forgiven for thinking this article was not very inspiring. If you’d like the current code, such as it is, check it out on GitHub:
https://github.com/damonrpayne/Shinto/tree/master/HandWaver.Shinto
Over the course of the following articles, I will lay out useful features that resurrect some of my more popular Silverlight articles.