コード例 #1
0
ファイル: Database.cs プロジェクト: leherv/ORM
        public List <T> ExecuteInsert <T>(InsertStatement <T> statement)
        {
            using var connection = _connection.Invoke();
            connection.Open();
            using IDbTransaction transaction = connection.BeginTransaction();
            using var command   = connection.CreateCommand();
            command.CommandText = statement.AsSqlString();
            command.Transaction = transaction;
            PrepareStatement(statement, command);

            try
            {
                var reader = command.ExecuteReader();

                var entity = statement._entityExecutedOn;
                var pkCol  = entity.PkColumn;
                var pocos  = statement._pocos;
                var cache  = _ctx.Cache;

                var enumerator = pocos.GetEnumerator();
                // now we set the pks the db returned on our pocos and add them to the cache
                while (reader.Read() && enumerator.MoveNext())
                {
                    var poco = enumerator.Current;
                    var pk   = reader[pkCol.Name];
                    pkCol.PropInfo.SetMethod.Invoke(poco, new[] { pk });
                    var cacheEntry = cache.GetOrInsert(entity, (long)pk, poco);

                    // now we fill originalPoco
                    foreach (var col in entity.CombinedColumns())
                    {
                        if (col.IsDbColumn)
                        {
                            if (col.IsShadowAttribute)
                            {
                                // TODO: maybe no entry?
                                cacheEntry.ShadowAttributes[col.Name] = null;
                            }
                            else
                            {
                                var value = col.PropInfo.GetMethod.Invoke(poco, new object[0]);
                                // fill the originalEntries with values for changeTracking later
                                if (!cacheEntry.OriginalPoco.ContainsKey(col.Name))
                                {
                                    cacheEntry.OriginalPoco.Add(col.Name, value);
                                }
                            }
                        }
                    }
                    LazyLoadInjector.InjectLazyLoader <T>(poco, _ctx, statement._entityExecutedOn);
                }
                reader.Close();
                transaction.Commit();
                return(pocos);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
                Console.WriteLine("  Message: {0}", ex.Message);
                transaction.Rollback();
                throw ex;
            }
        }