using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace IQToolkitContrib {
public partial class MemoryRepository : ARepository {
private List<object> entities = new List<object>();
protected override string GetPrimaryKeyPropertyName<T>() {
return Path.GetExtension(typeof(T).FullName).Substring(1) + "Id";
}
protected virtual void SetIdentityValue<T>(T entity) where T : class {
PropertyInfo pi = typeof(T).GetProperty(this.GetPrimaryKeyPropertyName<T>());
switch (pi.PropertyType.FullName) {
case "System.Int32":
case "System.Int64":
long id = Convert.ToInt64(pi.GetValue(entity, null));
if (id <= 0) {
pi.SetValue(entity, this.List<T>().Count() + 1, null);
}
break;
case "System.String":
if (string.IsNullOrEmpty(pi.GetValue(entity, null) as string)) {
pi.SetValue(entity, (this.List<T>().Count() + 1).ToString(), null);
}
break;
case "System.Guid":
Guid guidId = (Guid)pi.GetValue(entity, null);
if (guidId == default(Guid)) {
pi.SetValue(entity, Guid.NewGuid(), null);
}
break;
default:
throw new NotImplementedException(string.Format("PropertyType {0} not handled.", pi.PropertyType.FullName));
}
}
public override T Get<T>(object id) {
return this.List<T>().FirstOrDefault(this.CreateGetExpression<T>(id));
}
public override IQueryable<T> List<T>() {
return this.entities.OfType<T>().AsQueryable();
}
public override void Insert<T>(T entity) {
if (entity is IValidate) {
((IValidate)entity).Validate();
}
this.SetIdentityValue<T>(entity);
this.entities.Add(entity);
}
public override void Update<T>(T entity) {
if (entity is IValidate) {
((IValidate)entity).Validate();
}
string primaryKeyPropertyName = this.GetPrimaryKeyPropertyName<T>();
PropertyInfo pi = typeof(T).GetProperty(primaryKeyPropertyName);
object id = pi.GetValue(entity, null);
T originalEntity = this.Get<T>(id);
var properties = typeof(T).GetProperties();
foreach (var prop in properties) {
if (prop.CanWrite && prop.Name != primaryKeyPropertyName) {
var value = prop.GetValue(entity, null);
prop.SetValue(originalEntity, value, null);
}
}
}
public override void Delete<T>(T entity) {
this.entities.Remove(entity);
}
}
}