COA.EnterpriseServices/COA.EnterpriseServices.DataAccess.QuickBase/RecordMap.cs

93 lines
3.0 KiB
C#

using COA.Common;
using COA.PartnerApis.QuickBase;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace COA.EnterpriseServices.DataAccess.QuickBase
{
/// <summary>
/// Represents a map between a CLR type, its QuickBase table, and fields
/// </summary>
internal abstract class RecordMap
{
internal Type ItemType { get; set; }
internal string Table { get; set; }
internal ICollection<FieldMap> FieldMaps { get; } = new List<FieldMap>();
}
internal class RecordMap<TEntity, TEnumFieldMap> : RecordMap where TEntity : IRecord where TEnumFieldMap : Enum
{
internal RecordMap()
{
ItemType = typeof(TEntity);
var tableNameAttribute = typeof(TEnumFieldMap).GetCustomAttribute<QuickBaseNameAttribute>();
if (tableNameAttribute != null)
{
Table = tableNameAttribute.Name;
}
}
/// <summary>
/// Adds a propery mapping for an entity property
/// </summary>
/// <param name="property"></param>
/// <param name="field"></param>
/// <returns></returns>
internal RecordMap<TEntity, TEnumFieldMap> WithProperty(Expression<Func<TEntity, object>> property, TEnumFieldMap field)
{
if (property.Body is MemberExpression memberExpression)
{
FieldMaps.Add(new FieldMap
{
PropertyName = memberExpression.Member.Name,
FieldId = field.To<int>()
});
}
else if (property.Body is UnaryExpression unaryExpression && unaryExpression.Operand is MemberExpression unaryMemberExpression)
{
FieldMaps.Add(new FieldMap
{
PropertyName = unaryMemberExpression.Member.Name,
FieldId = field.To<int>()
});
}
return this;
}
/// <summary>
/// Adds default property mappings for common entity fields
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TEnumFieldMap"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
internal RecordMap<TEntity, TEnumFieldMap> WithDefaults()
{
FieldMaps.Add(new FieldMap
{
PropertyName = nameof(IRecord.Id),
FieldId = PartnerApis.QuickBase.Constants.RecordIdFieldId
});
FieldMaps.Add(new FieldMap
{
PropertyName = nameof(IRecord.Created),
FieldId = PartnerApis.QuickBase.Constants.DateCreatedFieldId
});
FieldMaps.Add(new FieldMap
{
PropertyName = nameof(IRecord.Modified),
FieldId = PartnerApis.QuickBase.Constants.DateModifiedFieldId
});
return this;
}
}
}