Example #1
0
        public void CreateEntity(T entity)
        {
            var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .Where(o => o.GetCustomAttribute <ColumnAttribute>() != null);
            var          cols     = new List <string>();
            var          vals     = new List <string>();
            var          parms    = new Dictionary <string, object>();
            PropertyInfo identity = null;
            var          n        = 0;

            foreach (var prop in props)
            {
                if (identity == null)
                {
                    var hasIdentity = prop.GetCustomAttributes <Attribute>().Any();
                    identity = hasIdentity ? prop : null;
                    if (hasIdentity)
                    {
                        continue;
                    }
                }

                var val = prop.GetValue(entity);
                if (val != null)
                {
                    cols.Add(prop.Name.ToLower());
                    vals.Add("@i" + n);
                    parms.Add("i" + n, val);
                    n++;
                }
            }

            var colsClause   = cols.Join(", ");
            var valuesClause = vals.Join(", ");
            var returning    = identity == null ? "" : string.Format(Dialect.ReturningIdentity, identity.Name.ToLower());

            var query = props.Count() > 1 ? $"insert into {Table}({colsClause}) values({valuesClause}) {returning}" : string.Format(Dialect.InsertDefault, Table) + " " + returning;

            using (IDbConnection db = new SqlConnection(connectionManager.GetConnectionString()))
            {
                var ret = db.ExecuteScalar(query, parms);

                if (identity != null)
                {
                    identity.SetValue(entity, identity.PropertyType == typeof(Int32) ? Convert.ToInt32(ret) : ret);
                }
            }
        }
Example #2
0
        public IEnumerable <T> ExucuteQuery <T>(string query, object param = null)
        {
            using (IDbConnection db = new SqlConnection(connectionManager.GetConnectionString()))
            {
                IEnumerable <T> result = db.Query <T>(query, param).ToList();

                return(result);
            }
        }