Ejemplo n.º 1
0
        public static T Get <T>(Container container, IEntityRequestContext context, IEntityInfo info, string primaryKey, IDBConnection database) where T : class, IEntityIdentity
        {
            using (Logger.CreateTrace(LoggingBoundaries.ServiceBoundary, typeof(SqlQuery), "Get"))
            {
                try
                {
                    var view = $"[{info.Module}].[VW_{info.Entity.ToUpperInvariant()}]";

                    var keyValues = primaryKey.Split('|').ToList();

                    var keys       = new List <string>();
                    var parameters = new List <DbParameter>();
                    var idx        = 0;
                    foreach (var property in info.Properties)
                    {
                        idx++;
                        var val = property.Value;
                        if (!val.IsKey.HasValue || (val.IsKey.HasValue && !val.IsKey.Value))
                        {
                            continue;
                        }

                        keys.Add($"{property.Key} = @val{idx}");
                        parameters.Add(database.CreateParameter($"@val{idx}", keyValues[0]));
                    }

                    var where = string.Join(" AND ", keys);

                    using (database)
                    {
                        var command = database.CreateCommand($"SELECT * FROM {view} WHERE {where}", CommandType.Text);
                        foreach (var parameter in parameters)
                        {
                            command.AddParameter(parameter);
                        }

                        var entity = new Entity();

                        var factory = container.GetInstance <IEntityCreateFactory>();
                        T   item    = factory.CreateNew(info) as T;

                        command.ExecuteReader(dataReader =>
                        {
                            if (!PopulateEntity(item, info, dataReader, true))
                            {
                                item = null;
                            }
                        });

                        return(item);
                    }
                }
                catch (Exception ex)
                {
                    if (Logger.HandleException(LoggingBoundaries.ServiceBoundary, ex))
                    {
                        throw;
                    }
                }
            }

            return(null);
        }