Skip to content

Instantly share code, notes, and snippets.

@ilyapalkin
Last active August 29, 2015 13:55
Show Gist options
  • Save ilyapalkin/8711592 to your computer and use it in GitHub Desktop.
Save ilyapalkin/8711592 to your computer and use it in GitHub Desktop.
Setting the identity of a Domain Entity
public class Entity
{
private int? id;
public int Id
{
get
{
return id.Value;
}
}
public Entity()
{ }
public static void SetId(Entity entity, int id)
{
entity.id = id;
}
}
public static class EntityHelper
{
/// <summary>
/// Sets the id of the entity using reflection.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="entity">The entity with Id property.</param>
/// <param name="id">The id value to be set to.</param>
/// <returns>
/// Entity with updated 'Id'
/// </returns>
public static TEntity WithId<TEntity>(this TEntity entity, int id)
where TEntity : Entity
{
SetId(entity, id);
return entity;
}
/// <summary>
/// Sets the id of the entity using reflection.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="entity">The entity with Id property.</param>
/// <param name="id">The id value to be set to.</param>
/// <exception cref="System.Exception">'id' private field cannot be found.</exception>
private static void SetId<TEntity>(TEntity entity, int id)
where TEntity : Entity
{
var idProperty = GetField(entity.GetType(), "id", BindingFlags.NonPublic | BindingFlags.Instance);
if (idProperty == null)
{
throw new Exception("'id' private field cannot be found.");
}
idProperty.SetValue(entity, id);
}
/// <summary>
/// Gets the field info.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="fieldName">Name of the field.</param>
/// <param name="bindibgAttr">Specifies flags that control binding and the way in which the search for members and types is conducted by reflection.</param>
/// <returns>
/// Null or found field info.
/// </returns>
public static FieldInfo GetField(Type type, string fieldName, BindingFlags bindibgAttr)
{
return type != null
? (type.GetField(fieldName, bindibgAttr) ?? GetField(type.BaseType, fieldName, bindibgAttr))
: null;
}
}
[TestClass]
public class SetIdentityTests
{
[TestMethod]
public void SetIdentity_ViaStaticMethod()
{
var target = new Entity();
Entity.SetId(target, 100500);
target.Id.Should().Be(100500);
}
[TestMethod]
public void SetIdentity_ViaReflection()
{
var target = new Entity().WithId(100500);
target.Id.Should().Be(100500);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment