/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="config"></param> /// <param name="mapping"></param> public static void AddEntityMapping <T>(this FluentMapConfiguration config, IEntityMap <T> mapping) where T : class, IEntity { if (!FluentMapper.EntityMaps.ContainsKey(mapping.GetType())) { config.AddMap(mapping); } }
internal IList <T> ExecuteReader <T>(IEntityMap entMap, DbConnection dbConn, ISession session, SqlQueryBody sql, int limit, int offset, out long total, params QueryParam[] paramArray) { total = 0; var dialect = session.SessionFactory.DbSettings.SqlDialect; var serializer = session.SessionFactory.DataSerializer; string countSql = BuildCountSql(session, sql, limit, offset); string sqlWithPaging = sql.ToString(dialect, new PagingInfo() { Limit = limit, Offset = offset }); string sqlToRun = string.Format("{0};\n\r{1};", countSql, sqlWithPaging); using (var dataReader = session.DataAccess.ExecuteReader(dbConn, session.CurrentTransaction, sqlToRun, paramArray)) { //First resultset contains the count while (dataReader.Read()) { total = serializer.ReadFieldData <long>(0, dataReader); //we only expect 1 row of data to be returned, so let's break out of the loop. break; } //move to the next result set which contains the entities dataReader.NextResult(); var entities = serializer.SerializeAll <T>(dataReader, entMap, sql.QueryMap); return(entities); } }
/// <summary> /// Serializes all. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="dataReader">The data reader.</param> /// <param name="entityMap">The entity map.</param> /// <param name="queryMap">The query map.</param> /// <returns></returns> /// <exception cref="GoliathDataException">unknown factory method</exception> public IList <TEntity> SerializeAll <TEntity>(DbDataReader dataReader, IEntityMap entityMap, TableQueryMap queryMap = null) { Delegate dlgMethod; Type type = typeof(TEntity); Func <DbDataReader, IEntityMap, TableQueryMap, IList <TEntity> > factoryMethod = null; if (factoryList.TryGetValue(type, out dlgMethod)) { factoryMethod = dlgMethod as Func <DbDataReader, IEntityMap, TableQueryMap, IList <TEntity> >; if (factoryMethod == null) { throw new GoliathDataException("unknown factory method"); } } else { factoryMethod = CreateSerializerMethod <TEntity>(entityMap); factoryList.TryAdd(type, factoryMethod); } IList <TEntity> entityList = factoryMethod(dataReader, entityMap, queryMap); return(entityList); }
public ModelConfiguration(string assemblyName, string folderName) { try { var assemblyModel = Assembly.Load(assemblyName); foreach (Type type in assemblyModel.ExportedTypes) { if (type.Namespace.Equals(assemblyName + "." + folderName)) { if (!type.IsEnum) { IEntityMap entityMap = Activator.CreateInstance(typeof(EntityMap <>).MakeGenericType(type)) as IEntityMap; Configuration.Mappings.Add(type.Name, entityMap); } else { IEnumMap enumMap = Activator.CreateInstance(typeof(EnumMap), type) as IEnumMap; Configuration.Mappings.Add(type.Name, enumMap); } } } } catch { throw; } }
/// <summary> /// Gets the entity accessor and cache it. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="entMap">The ent map.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">entityType</exception> public EntityAccessor GetEntityAccessor(Type entityType, IEntityMap entMap) { if (entityType == null) { throw new ArgumentNullException(nameof(entityType)); } EntityAccessor entityAccessor = null; string key = entityType.FullName; lock (padLock) { if (store.TryGetValue(key, out entityAccessor)) { return(entityAccessor); } entityAccessor = new EntityAccessor(entityType); if (entMap != null) { entityAccessor.Load(entMap); } Add(key, entityAccessor); } return(entityAccessor); }
public FileSystemIndexConfigurator(string directory, Model model, string name) { _directory = directory; _model = model; _entityMap = model.GetEntity(name); _indexes = new IndexConfigurationConverter(model, _entityMap).Convert(); }
private static bool HasXmlTypeConverter(PropertyInfo property, IEntityMap entityMap) { var result = false; if (entityMap != null) { var propertyMap = entityMap.Properties.FirstOrDefault(p => p.Property.PropertyName == property.Name); if (propertyMap != null && propertyMap.Property.Converter != null) { result = propertyMap.Property.Converter == typeof(XmlTypeConverter) || propertyMap.Property.Converter == typeof(XmlReaderTypeConverter); } } if (result) { return(true); } var customAttributes = property.GetCustomAttributes(typeof(TypeConverterAttribute), false).Cast <TypeConverterAttribute>(); foreach (var attribute in customAttributes) { result = attribute.TypeConverterType == typeof(XmlTypeConverter) || attribute.TypeConverterType == typeof(XmlReaderTypeConverter); if (result) { break; } } return(result); }
public string Remove(T entity) { string sql = query; if (string.IsNullOrEmpty(EntityMap.PrimaryKeyName)) { foreach (var keyValue in EntityMap.Entities) { IEntityMap entityMap = keyValue.Value; object obj = EntityMap.Type.GetProperty(keyValue.Key).GetValue(entity); if (obj != null) { if (!string.IsNullOrEmpty(entityMap.PrimaryKeyName)) { var value = entityMap.Type.GetProperty(entityMap.PrimaryKeyName).GetValue(obj); sql = sql.Replace("{" + keyValue.Key + "}", DataFormater.ParseToSQL(value)); } } } } else { var value = EntityMap.Type.GetProperty(EntityMap.PrimaryKeyName).GetValue(entity); sql = sql.Replace("{Id}", DataFormater.ParseToSQL(value)); } return(sql); }
private static bool HasListTypeConverter(PropertyInfo property, IEntityMap entityMap) { bool result = false; if (entityMap != null) { var propertyMap = entityMap.Properties.FirstOrDefault(p => p.Property.PropertyName == property.Name); if (propertyMap != null && propertyMap.Property.Converter != null) { result = propertyMap.Property.Converter.GetGenericTypeDefinition() == typeof(ListConverter <>); } } if (result) { return(true); } var customAttributes = property.GetCustomAttributes(typeof(TypeConverterAttribute), false).Cast <TypeConverterAttribute>(); foreach (var attribute in customAttributes) { result = attribute.TypeConverterType.IsGenericType && attribute.TypeConverterType.GetGenericTypeDefinition() == typeof(ListConverter <>); if (result) { break; } } return(result); }
/// <summary> /// Adds the specified <see cref="T:Dapper.FluentMap.Mapping.EntityMap"/> to the configuration of Dapper.FluentMap. /// </summary> /// <typeparam name="TEntity">The type argument of the entity.</typeparam> /// <param name="mapper"> /// An instance of the <see cref="T:Dapper.FluentMap.Mapping.IEntityMap"/> interface containing the /// entity mapping configuration. /// </param> public void AddMap <TEntity>(IEntityMap <TEntity> mapper) where TEntity : class { if (FluentMapper.EntityMaps.TryAdd(typeof(TEntity), mapper)) { FluentMapper.AddTypeMap <TEntity>(); } }
public void AddMap <TEntity>(IEntityMap <TEntity> mapper) where TEntity : class { if (!FluentMapper.EntityMaps.TryAdd(typeof(TEntity), mapper)) { throw new InvalidOperationException($"Adding entity map for type '{typeof(TEntity)}' failed. The type already exists. Current entity maps: "); } }
public Query(IEntityMap entityMap) { QueryTranslator = new QueryTranslator <T>(entityMap); EntityMap = entityMap; BuidQuery(); BuildCollectionsQuery(); }
internal IList <T> ExecuteReader <T>(IEntityMap entMap, DbConnection dbConn, ISession session, string sql, TableQueryMap queryMap, params QueryParam[] paramArray) { using (var dataReader = session.DataAccess.ExecuteReader(dbConn, session.CurrentTransaction, sql, paramArray)) { var entities = session.SessionFactory.DataSerializer.SerializeAll <T>(dataReader, entMap, queryMap); return(entities); } }
protected void DeleteCollection <TList>(IEnumerable <TList> collection, IEntityMap map) where TList : class, IEntity, new() { foreach (var entity in collection) { innerRepository.Delete <T>(entity.Id); } }
internal void AddEntity(IEntityMap entity) { if (entitiesMaps == null) { entitiesMaps = new List <IEntityMap>(); } entitiesMaps.Add(entity); }
void FillEntities(object entity) { Type type = entity.GetType(); IEntityMap entityMap; Cfg.Configuration.Mappings.TryGetValue(type.Name, out entityMap); foreach (var keyValuePair in entityMap.Entities) { if (CurrentType != keyValuePair.Value.Type && !keyValuePair.Value.Type.IsEnum) { IEntityMap foreignEntity = keyValuePair.Value; object obj = type.GetProperty(keyValuePair.Key).GetValue(entity); if (obj != null) { if (!string.IsNullOrEmpty(foreignEntity.PrimaryKeyName)) { object id = foreignEntity.Type.GetProperty(foreignEntity.PrimaryKeyName).GetValue(obj); string sql = foreignEntity.ForeignSelect + "WHERE _this." + foreignEntity.PrimaryKeyName + " = " + DataFormater.ParseToSQL(id) + ";"; foreach (var keyValue in foreignEntity.Entities) { IEntityMap map = keyValue.Value; using (IDbCommand command = CreateCommand(sql)) { using (IDataReader reader = command.ExecuteReader()) { if (reader.Read()) { object o = Activator.CreateInstance(map.Type); foreach (var kv in map.ColumnNames) { string propertyName = kv.Key; var value = reader[keyValue.Key + "." + propertyName]; propertyName = propertyName.Replace(keyValue.Key + ".", ""); PropertyInfo property = map.Type.GetProperty(propertyName); property.SetValue(o, DataFormater.ParseToData(property, value)); } foreignEntity.Type.GetProperty(keyValue.Key).SetValue(obj, o); reader.Close(); reader.Dispose(); command.Dispose(); FillEntities(o); } } } } } else { } } } else { // la entidad es del mismo tipo que T } } }
private void Cascade <T>(IEntityMap <T> entityMap, T entity) where T : class, IEntity, new() { var listMaps = entityMap.PropertyMaps.Where(x => x is IListPropertyMap <T>).Cast <IListPropertyMap <T> >(); foreach (var map in listMaps) { map.Cascade(this, entity); } }
private static void ApplyEntityMap(RuntimeTypeModel typeModel, IEntityMap entityMap) { var metaType = typeModel.Add(entityMap.EntityType, false); foreach (var propertyMap in entityMap.Properties) { metaType.Add(propertyMap.Index, propertyMap.PropertyName); } }
private static bool IsWrappable(PropertyInfo property, IEntityMap entityMap) { var propertyType = property.PropertyType; return(Reflector.IsSimpleType(propertyType) || propertyType == typeof(byte[]) || (Reflector.IsSimpleList(propertyType) && HasListTypeConverter(property, entityMap)) || (Reflector.IsXmlType(propertyType) && HasXmlTypeConverter(property, entityMap))); }
void IForeignKeyMap <T> .ColumnName(string columnName) { if (CurrentProperty != null) { if (CurrentProperty.PropertyType.Namespace.Equals("System")) { Keys.Remove(CurrentProperty.Name); Keys.Add(CurrentProperty.Name, columnName); } else { IEntityMap entity = Activator.CreateInstance(typeof(EntityMap <>).MakeGenericType(CurrentProperty.PropertyType)) as IEntityMap; string propertyName = CurrentProperty.Name; if (string.IsNullOrEmpty(entity.PrimaryKeyName) && entity.ForeignKeys.Count > 0) { ForeignKeys.Remove(propertyName); if (string.IsNullOrEmpty(CurrentForeignPropertyName)) { ForeignKeys.Add(columnName, columnName); } else { ForeignKeys.Remove(propertyName); ForeignKeys.Add(propertyName, columnName); CurrentForeignPropertyName = null; CurrentProperty = null; } } else { ForeignKeys.Remove(propertyName); ForeignKeys.Add(propertyName, columnName); } } } else { if (!string.IsNullOrEmpty(CurrentForeignPropertyName)) { if (CurrentForeignPropertyName.Contains(".")) { string[] entities = CurrentForeignPropertyName.Split('.'); PropertyInfo property = Type.GetProperty(entities[0]); if (property != null) { IEntityMap entity = Activator.CreateInstance(typeof(EntityMap <>).MakeGenericType(property.PropertyType)) as IEntityMap; if (string.IsNullOrEmpty(entity.PrimaryKeyName)) { ForeignKeys.Remove(property.Name); } } } ForeignKeys.Add(CurrentForeignPropertyName, columnName); } } }
public void Add <T>(IEntityMap <T> map) where T : TSchema { _entityMaps[map.EntityType.EntityType] = map; if (map.EntityType.EntityTypeSelector != null) { _entityTypeSelectorFactory.Add(map.EntityType); } }
public override void Apply(IEntityMapBuilder <TEntity, TSchema> builder) { IEntityMap <TEntityValue> entityMap = builder.GetEntityMap <TEntityValue>(); var mapper = new SingleSliceValueEntityProperty <TEntity, TEntityValue>(builder.ImplementationType, Property.Name, Position, x => Factory(x, entityMap)); ITextSliceProvider <TEntity> provider = new EntityValueSliceProvider <TEntity, TEntityValue>(Property, entityMap); builder.Add(mapper, provider); }
internal IList <T> ExecuteReader <T>(IEntityMap entMap, DbConnection dbConn, ISession session, SqlQueryBody sql, int limit, int offset, params QueryParam[] paramArray) { using (var dataReader = session.DataAccess.ExecuteReader(dbConn, session.CurrentTransaction, sql.ToString(session.SessionFactory.DbSettings.SqlDialect, new PagingInfo() { Limit = limit, Offset = offset }), paramArray)) { var entities = session.SessionFactory.DataSerializer.SerializeAll <T>(dataReader, entMap, sql.QueryMap); return(entities); } }
public Modify(IEntityMap entityMap) { EntityMap = entityMap; query = "UPDATE " + entityMap.TableName + " SET "; foreach (var keyValueColumn in entityMap.ColumnNames) { if (keyValueColumn.Key != entityMap.PrimaryKeyName) { query += keyValueColumn.Value + " = {" + keyValueColumn.Key + "}, "; } else { if (!entityMap.IsAutoincrement) { query += keyValueColumn.Value + " = {" + keyValueColumn.Key + "}, "; } } } query += "-"; query = query.Replace(", -", " "); query += "WHERE "; if (string.IsNullOrEmpty(entityMap.PrimaryKeyName)) { foreach (var keyValue in entityMap.ForeignKeys) { query += keyValue.Value + " = {" + keyValue.Key + "} AND "; } foreach (var keyValue in entityMap.Keys) { query += keyValue.Value + " = {" + keyValue.Key + "} AND "; } query += "-"; query = query.Replace(" AND -", ";"); } else { if (entityMap.IsAutoincrement) { query += entityMap.PrimaryKeyName + " = {Id};"; } else { foreach (var keyValue in entityMap.ForeignKeys) { query += keyValue.Value + " = {" + keyValue.Key + "} AND "; } foreach (var keyValue in entityMap.Keys) { query += keyValue.Value + " = {" + keyValue.Key + "} AND "; } query += entityMap.PrimaryKeyName + " = {Id};"; } } }
public override void Apply(IEntityMapBuilder <TEntity, TSchema> builder) { IEntityMap <TEntityValue> entityMap = builder.GetEntityMap <TEntityValue>(); var property = new ValueListEntityProperty <TEntity, TEntityValue>(builder.ImplementationType, Property.Name, Position, x => new EntityValueList <TEntityValue>(x, entityMap), _sliceFactory); ITextSliceProvider <TEntity> provider = new ValueListSliceProvider <TEntity, TEntityValue>(Property, new EntityValueFormatter <TEntityValue>(entityMap)); builder.Add(property, provider); }
/// <summary> /// Adds the specified <see cref="T:AA.Dapper.FluentMap.Mapping.EntityMap"/> to the configuration of AA.Dapper.FluentMap. /// </summary> /// <typeparam name="TEntity">The type argument of the entity.</typeparam> /// <param name="mapper"> /// An instance of the <see cref="T:AA.Dapper.FluentMap.Mapping.IEntityMap"/> interface containing the /// entity mapping configuration. /// </param> public void AddMap <TEntity>(IEntityMap <TEntity> mapper) where TEntity : class { if (FluentMapper.EntityMaps.TryAdd(typeof(TEntity), mapper)) { FluentMapper.AddTypeMap <TEntity>(); } else { throw new InvalidOperationException($"Adding entity map for type '{typeof(TEntity)}' failed. The type already exists. Current entity maps: " + string.Join(", ", FluentMapper.EntityMaps.Select(e => e.Key.ToString()))); } }
/// <summary> /// Loads the specified entity map. /// </summary> /// <param name="entityMap">The entity map.</param> /// <param name="propertiesInfo">The properties info.</param> /// <exception cref="System.ArgumentNullException">entityMap</exception> public void Load(IEntityMap entityMap, PropertyInfo[] propertiesInfo = null) { if (entityMap == null) { throw new ArgumentNullException(nameof(entityMap)); } if (IsReady) { return; } if (propertiesInfo == null) { propertiesInfo = EntityType.GetProperties(BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.Instance); } //EntityMap superEntityMap = null; if ((entityMap is EntityMap) && ((EntityMap)entityMap).IsSubClass) { var superEntityMap = entityMap.Parent.GetEntityMap(entityMap.Extends); Load(superEntityMap, propertiesInfo); } lock (padLock) { foreach (var pinfo in propertiesInfo) { var prop = entityMap.GetProperty(pinfo.Name); if (prop != null) { prop.ClrType = pinfo.PropertyType; var property = new PropertyAccessor { DeclaringType = EntityType, PropertyType = pinfo.PropertyType, PropertyName = prop.Name, GetMethod = pinfo.CreateDynamicGetMethodDelegate(), SetMethod = pinfo.CreateDynamicSetMethodDelegate(), }; if (!Properties.ContainsKey(property.PropertyName)) { Properties.Add(property.PropertyName, property); } } } IsReady = true; } }
private void ConvertRecursive(List<IndexConfiguration> list, IEntityMap entityMap, string left) { foreach (var index in entityMap.Indexes) { list.Add(new IndexConfiguration { UniqueName = CreatePath(left, index.UniqueName), Type = index.ValueType, EntityType = entityMap.EntityType }); } foreach (var property in entityMap.Properties) { // TODO: Create sub indexes recursively } }
public Persist(IEntityMap entityMap) { EntityMap = entityMap; string columnNames = string.Empty, values = string.Empty; foreach (var keyValueColumn in EntityMap.ColumnNames) { if (keyValueColumn.Key != EntityMap.PrimaryKeyName) { columnNames += keyValueColumn.Value + ", "; values += "{" + keyValueColumn.Key + "}, "; } else { if (!EntityMap.IsAutoincrement) { columnNames += keyValueColumn.Value + ", "; values += "{" + keyValueColumn.Key + "}, "; } } } foreach (var keyValue in EntityMap.ForeignKeys) { columnNames += keyValue.Value + ", "; values += "{" + keyValue.Key + "}, "; } if (string.IsNullOrEmpty(EntityMap.PrimaryKeyName)) { foreach (var keyValue in EntityMap.Keys) { if (!EntityMap.ColumnNames.ContainsKey(keyValue.Key)) { columnNames += keyValue.Value + ", "; values += "{" + keyValue.Key + "}, "; } else { } } } columnNames += "-"; columnNames = columnNames.Replace(", -", ""); values += "-"; values = values.Replace(", -", ""); Query = "INSERT INTO " + EntityMap.TableName + " (" + columnNames + ") VALUES (" + values + ");"; }
private QueryCollection CreateQueryCollection(IEntityMap entityMap) { var collection = new QueryCollection(); collection.Properties = entityMap.PropertyMaps.Select(propertyMap => { var queryType = QueryType.All ^ propertyMap.IgnoredQuery; return(propertyMap.PropertyName, propertyMap.ColumnName, queryType); }); collection.TableName = entityMap.TableName; collection.PropertyColumns = entityMap.PropertyMaps.ToDictionary(x => x.PropertyName, x => x.ColumnName); collection.Queries = GenerateQueries(collection.Properties, collection.TableName, collection.PropertyColumns); return(collection); }
/// <summary> /// Maps an entities mapping properties to column schema's /// </summary> /// <param name="map">The entity map</param> /// <returns>An array of column schema's</returns> private DataColumnSchema[] MapTableProperties ( IEntityMap map ) { var columnSchemas = new List <DataColumnSchema>(); foreach (var property in map.Properties) { var column = new DataColumnSchema ( property.ColumnName, property.Type ); columnSchemas.Add(column); } return(columnSchemas.ToArray()); }
public ModelConfiguration Add <T>() where T : class { try { Type type = typeof(T); if (type.BaseType.Name != typeof(ClassMap <>).Name) { throw new Exception("El tipo [" + type + "] debe ser una clase heredada del tipo [" + typeof(ClassMap <>) + "]"); } string entityKey = type.BaseType.GetGenericArguments()[0].Name; Configuration.Mappings.Remove(entityKey); IEntityMap entityMap = Activator.CreateInstance(type) as IEntityMap; Configuration.Mappings.Add(entityKey, entityMap); return(this); } catch { throw; } }
/// <summary> /// Constructor </summary> /// <remarks> Public Constructor.</remarks> /// <param name="anEntityMap">IEntityMap instance.</param> public AddressTemplate(IEntityMap anEntityMap) : base(anEntityMap) { }
public void AddParameter(Type entityType, string entityAlias) { var parameterExpression = _parameters.FirstOrDefault(p => p.Name == entityAlias); if (parameterExpression != null) { _expressions.Push(parameterExpression); return; } parameterExpression = Expression.Parameter(entityType, entityAlias); _expressions.Push(parameterExpression); _parameters.Push(parameterExpression); if (_entityParameter == null && !IsValue(entityType)) { _entityParameter = parameterExpression; _entityMap = _model.GetEntity(entityType); } }
/// <summary> /// Constructor </summary> /// <remarks> Public Constructor.</remarks> /// <param name="anEntityMap">IEntityMap instance.</param> public CustomerTemplate(IEntityMap anEntityMap) : base(anEntityMap) { }
/// <summary> /// Constructor </summary> /// <remarks> Public Constructor.</remarks> /// <param name="anEntityMap">IEntityMap instance.</param> public OrderItemTemplate(IEntityMap anEntityMap) : base(anEntityMap) { }
/// <summary> /// Constructor </summary> /// <remarks> Public Constructor.</remarks> /// <param name="anEntityMap">IEntityMap instance.</param> public StatusTemplate(IEntityMap anEntityMap) : base(anEntityMap) { }
/// <summary> /// Constructor </summary> /// <remarks> Public Constructor.</remarks> /// <param name="anEntityMap">IEntityMap instance.</param> public InventoryTemplate(IEntityMap anEntityMap) : base(anEntityMap) { }
internal DbMapping(ITrackerContext context, Type entityType) { _entityType = entityType; _entityMap = (context as DbContext).Db(_entityType); }
/// <summary> /// Constructor </summary> /// <remarks> Public Constructor.</remarks> /// <param name="anEntityMap">IEntityMap instance.</param> public ProductTemplate(IEntityMap anEntityMap) : base(anEntityMap) { }
public IndexConfigurationConverter(Model model, IEntityMap primaryEntity) { _model = model; _primaryEntity = primaryEntity; }
public MemoryIndexConfigurator(Model model, string name) { _model = model; _entityMap = model.GetEntity(name); _indexes = new IndexConfigurationConverter(model, _entityMap).Convert(); }