/// <summary>Pre save changes.</summary>
        /// <param name="audit">The audit to use to add changes made to the context.</param>
        /// <param name="context">The context used to audits and saves all changes made.</param>
        public static void PreSaveChanges(Audit audit, DbContext context)
        {
#if EF5 || EF6
            var objectContext = context.GetObjectContext();
            objectContext.DetectChanges();

            var changes = objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted);

            foreach (var objectStateEntry in changes)
            {
                if (objectStateEntry.IsRelationship)
                {
                    if (objectStateEntry.State == EntityState.Added && audit.Configuration.IncludeRelationAdded)
                    {
                        AuditRelationAdded(audit, objectStateEntry);
                    }
                    else if (objectStateEntry.State == EntityState.Deleted && audit.Configuration.IncludeRelationDeleted)
                    {
                        AuditRelationDeleted(audit, objectStateEntry);
                    }
                }
                else
                {
                    if (objectStateEntry.State == EntityState.Added && audit.Configuration.IncludeEntityAdded)
                    {
                        AuditEntityAdded(audit, objectStateEntry);
                    }
                    else if (objectStateEntry.State == EntityState.Deleted && audit.Configuration.IncludeEntityDeleted)
                    {
                        AuditEntityDeleted(audit, objectStateEntry);
                    }
                    else if (objectStateEntry.State == EntityState.Modified && audit.Configuration.IncludeEntityModified)
                    {
                        AuditEntityModified(audit, objectStateEntry);
                    }
                }
            }
#elif EF7
            context.ChangeTracker.DetectChanges();
            var manager = context.ChangeTracker.GetStateManager();
            var entries = manager.Entries;

            foreach (var entry in entries)
            {
                if (entry.EntityState == EntityState.Added)
                {
                    
                }
                else if (entry.EntityState == EntityState.Deleted)
                {

                }
                else if (entry.EntityState == EntityState.Modified)
                {
                    
                }
            }
#endif

        }
示例#2
0
        internal static object LoadStub(Type t, string primaryKeyName, object id, DbContext db)
        {
            var cachedEnt =
                    db.ChangeTracker.Entries().Where(x => ObjectContext.GetObjectType(x.Entity.GetType()) == t).SingleOrDefault(x =>
                    {
                        Type entType = x.Entity.GetType();
                        object value = entType.InvokeMember(primaryKeyName, System.Reflection.BindingFlags.GetProperty, null, x.Entity, new object[] { });

                        return value.Equals(id);
                    });

            if (cachedEnt != null)
            {
                return cachedEnt.Entity;
            }
            else
            {
                object stub = Activator.CreateInstance(t);

                t.InvokeMember(primaryKeyName, System.Reflection.BindingFlags.SetProperty, null, stub, new object[] { id });

                db.Entry(stub).State = EntityState.Unchanged;

                return stub;
            }
        }
示例#3
0
 public TransactionsHandler(DbContext dbContext, ICardAccountRepository cardAcountRepo, IGenericRepository<TransactionHistory> transactionLogRepo)
 {
     this.dbContext = dbContext;
     this.cardAcountRepo = cardAcountRepo;
     this.transactionLogRepo = transactionLogRepo;
     this.errors = new List<string>();
 }
        public MigrationResult Migrate(DbContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!context.IsAzureDatabase())
            {
                return new MigrationResult
                {
                    MigrationWasApplied = true,
                    Log = "Database is not an Azure SQL database so no action taken."
                };
            }

            var sql =
                $@"
alter database {context.Database.Connection.Database} 
modify (MAXSIZE = {MaxSize},
        EDITION = '{Edition}',
        SERVICE_OBJECTIVE = '{ServiceObjective}')";

            context.Database.ExecuteSqlCommand(sql);

            return new MigrationResult
            {
                MigrationWasApplied = true,
                Log = sql
            };
        }
示例#5
0
 /// <summary>
 /// 根据数据库类型获取适配器
 /// </summary>
 /// <param name="dbContext"></param>
 /// <returns></returns>
 public static DBAdapterBase GetDBAdapterBase(DbContext dbContext)
 {
     DBAdapterBase db = null;
     switch (dbContext.DBHelper.CurrentDBType)
     {
         case CoreHelper.DBType.MSSQL:
             db = new MSSQLDBAdapter(dbContext);
             break;
         case CoreHelper.DBType.MSSQL2000:
             db = new MSSQL2000DBAdapter(dbContext);
             break;
         case CoreHelper.DBType.ACCESS:
             break;
         case CoreHelper.DBType.MYSQL:
             db = new MySQLDBAdapter(dbContext);
             break;
         case CoreHelper.DBType.ORACLE:
             db = new ORACLEDBAdapter(dbContext);
             break;
     }
     if (db == null)
     {
         throw new Exception("找不到对应的DBAdapte" + dbContext.DBHelper.CurrentDBType);
     }
     return db;
 }
示例#6
0
        /// <summary>
        /// sample invocation code
        /// int codPers = 21024;
        /// string tipPers = "fiz";
        /// SqlCommand sqlCommand = new SqlCommand("dbo.GetSolduri");
        /// sqlCommand.CommandType = CommandType.StoredProcedure;
        /// sqlCommand.Parameters.AddWithValue("@codPers", codPers);
        /// sqlCommand.Parameters.AddWithValue("@tipPers", tipPers);
        /// return HelperController.SqlCommandToDynamicEntity(repository.Context, sqlCommand);
        /// </summary>
        /// <param name="context"></param>
        /// <param name="sqlCommand"></param>
        /// <returns></returns>
        public static List<object> SqlCommandToDynamicEntity(DbContext context, SqlCommand sqlCommand)
        {
            string dynamicEntity = "DynamicEntity";
            bool isFirstRow = true;
            AssemblyName assemblyName = new AssemblyName("MyAssembly");
            AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
            TypeBuilder typeBuilder = moduleBuilder.DefineType(dynamicEntity, TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass |
                                                    TypeAttributes.BeforeFieldInit, typeof(System.Object));

            List<object> entities = new List<object>();
            // Get the type contained in the name string
            Type type = typeBuilder.AsType();

            DataTable dt = new DataTable();

            ///sample invocation code
            //int codPers = 21024;
            //string tipPers = "fiz";
            //sqlCommand = new SqlCommand("dbo.GetSolduri");
            //sqlCommand.CommandType = CommandType.StoredProcedure;
            //sqlCommand.Parameters.AddWithValue("@codPers", codPers);
            //sqlCommand.Parameters.AddWithValue("@tipPers", tipPers);

            using (SqlConnection con = new SqlConnection(context.Database.Connection.ConnectionString))
            {
                using (sqlCommand)
                {
                    sqlCommand.Connection = con;
                    con.Open();
                    SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
                    da.Fill(dt);
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (isFirstRow)
                        {
                            isFirstRow = false;
                            foreach (DataColumn col in dt.Columns)
                            {
                                typeBuilder.DefineField(col.ColumnName, (dr[col]).GetType(), FieldAttributes.Public);
                            }

                            type = typeBuilder.CreateType();
                            var prop = type.GetFields().First().Name;
                        }
                        // create an instance of that type
                        object entity = Activator.CreateInstance(type);
                        foreach (DataColumn col in dt.Columns)
                        {
                            if (dr[col] == null || dr[col] == System.DBNull.Value) continue;
                            FieldInfo prop = type.GetField(col.ColumnName);
                            // Set the value of the given property on the given instance
                            prop.SetValue(entity, dr[col]);
                        }
                        entities.Add(entity);
                    }
                    return entities;
                }
            }
        }
示例#7
0
        public void SetUp()
        {
            DbContextBuilder<DbContext> builder = new DbContextBuilder<DbContext>("DefaultDb", new[] { "QV.Tests" }, true, true);
            context = builder.BuildDbContext();

            customerRepository = new QV.Tests.Data.Lab.CustomerRepository(context);
            repository = new QV.Data.EntityFramework.Lab.GenericRepository(context);
        }
示例#8
0
 public void TearDown()
 {
     if ((context != null) && (((IObjectContextAdapter)context).ObjectContext.Connection.State == System.Data.ConnectionState.Open))
     {
         ((IObjectContextAdapter)context).ObjectContext.Connection.Close();
         context = null;
     }
 }
示例#9
0
        public void SetUp()
        {
            var builder = new DbContextBuilder<DbContext>("DefaultDb", new[] { "Infrastructure.Tests" }, true, true);
            this.context = builder.BuildDbContext();

            this.customerRepository = new CustomerRepository(this.context);
            this.repository = new GenericRepository(this.context);
        }
示例#10
0
 public OperationRepository(DbContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context", "DbContext should not be empty");
     }
     Context = context;
 }
示例#11
0
        internal static void AssignStubx(object poco, DbContext db)
        {
            IEnumerable<PropertyMapping> piNeedStub = Mapper.StubsNeeded(poco.GetType());

            foreach (PropertyMapping pm in piNeedStub)
            {
                // pm.PropertyPoco.First().   e.g. Customer of Customer.CustomerId.    Customer is PropertyPoco[0], CustomerId is PropertyPoco[1]
                PropertyInfo pocoForeign = poco.GetType().GetProperty(pm.PropertyPoco[0], BindingFlags.Public | BindingFlags.Instance);
                if (pocoForeign == null) continue;

                object val = pocoForeign.GetValue(poco, null);

                if (val != null)
                {
                    PropertyInfo pocoForeignId = pocoForeign.PropertyType.GetProperty(pm.PropertyPoco.Last(), BindingFlags.Public | BindingFlags.Instance);

                    object id = pocoForeignId.GetValue(val, null);

                    pocoForeign.SetValue(poco, LoadStub(pocoForeign.PropertyType, pm.PropertyPoco.Last(), id, db), null);
                }
                else
                {
                    // foreign key is null'd

                    // nullable foreign key association
                    // http://www.codetuning.net/blog/post/Understanding-Entity-Framework-Associations.aspx

                    var dummy = pocoForeign.GetValue(poco, null); // work-around

                    pocoForeign.SetValue(poco, val, null);
                }

            }

            IEnumerable<PropertyInfo> piCollection =
                poco.GetType().GetProperties()
                .Where(x => x.PropertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(x.PropertyType));

            foreach (PropertyInfo item in piCollection)
            {
                PropertyInfo px = poco.GetType().GetProperty(item.Name, BindingFlags.Public | BindingFlags.Instance);

                // same property exists from dto to poco
                if (px != null)
                {
                    IList col = (IList)px.GetValue(poco, null);
                    if (col == null) continue;

                    Type dtoType = item.PropertyType.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>)).Single().GetGenericArguments()[0];

                    foreach (object elem in col)
                    {
                        db.AssignStub(elem);
                    }

                }
            }
        }
示例#12
0
 public void TearDown()
 {
     if ((this.context != null)
         && (((IObjectContextAdapter)this.context).ObjectContext.Connection.State == ConnectionState.Open))
     {
         ((IObjectContextAdapter)this.context).ObjectContext.Connection.Close();
         this.context = null;
     }
 }
示例#13
0
        public EventRepository(DbContext context)
        {
            if (context == null)
              {
            throw new ArgumentNullException("context");
              }

              _db = context as DevAgendaCtx;
        }
示例#14
0
 public void TestGetTheRightCopier3()
 {
     DbContext dc = new DbContext("SqlServer");
     dc.NewTransaction(delegate()
     {
         IDbBulkCopy c = dc.GetDbBulkCopy();
         Assert.IsNotNull(c);
         Assert.IsTrue(c is SqlServerBulkCopy);
     });
 }
示例#15
0
        //Ctor
        public SEORepository(DbContext _DbContext, string _TableName = "")
        {
            this.TableName = _TableName;

            if (_DbContext == null)
                throw new ArgumentNullException("DbContext");

            DbContext = _DbContext;
            DbSet = _DbContext.Set<SEO>();
        }
示例#16
0
        public BulkOperationProvider(DbContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            _context = context;

            //ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings[context.GetType().Name];
            _connectionString = context.Database.Connection.ConnectionString;
        }
示例#17
0
        public EF6UnitOfWorkTests()
        {
            DbConnection connection = Effort.DbConnectionFactory.CreateTransient();
            _context = new FooContext(connection);

            _unitOfWork = new Ef6UnitOfWork(_context, IsolationLevel.Unspecified);

            var repository = new BaseRepository<Foo>(_unitOfWork);
            _repositoryWriter = repository;
            _repositoryReader = repository;
        }
		/// <summary>
		/// Create News Media Content 
		/// </summary>
		/// <param name="newsMedia">newsMedia</param>
		/// <returns>Returns the news media content</returns>
         public NewsMedia Create(NewsMedia newsMedia)
         {
            using(var database = new DbContext(CONNECTION_NAME))
             {
                database.Set<NewsMedia>().Add(newsMedia);
                database.SaveChanges();

                return newsMedia;
             }

         }
        /// <summary>
        /// Initializes a new instance of the <see cref="AuditLogger"/> class.
        /// </summary>
        /// <param name="dbContext">The <see cref="DbContext"/> to create the <see cref="AuditLog"/> from.</param>
        /// <param name="configuration">The <see cref="AuditConfiguration"/> to use when creating the <see cref="AuditLog"/>.</param>
        public AuditLogger(DbContext dbContext, AuditConfiguration configuration)
        {
            if (dbContext == null)
                throw new ArgumentNullException("dbContext");

            var adapter = (IObjectContextAdapter)dbContext;
            _objectContext = adapter.ObjectContext;
            _configuration = configuration ?? AuditConfiguration.Default;

            AttachEvents();
        }
示例#20
0
        public BaseRepositoryTests()
        {
            DbConnection connection = DbConnectionFactory.CreateTransient();
            _context = new FooContext(connection);

            var repository = new BaseRepository<Foo>(new Ef6UnitOfWork(_context, IsolationLevel.Unspecified));
            _repositoryWriter = repository;
            _repositoryReader = repository;
            _repositoryWriterAsync = repository;
            _repositoryReaderAsync = repository;
        }
示例#21
0
 public static DbParameter[] GetCachedParameters(DbContext dbContext)
 {
     if (((dbContext == null) || (dbContext.Connection == null)) || (dbContext.CurrentCommand == null))
     {
         throw new ArgumentNullException("dbContext");
     }
     if ((dbContext.CurrentCommand.CommandType != CommandType.StoredProcedure) || string.IsNullOrEmpty(dbContext.CurrentCommand.CommandText))
     {
         throw new InvalidOperationException("命令不是存储过程,或没有设置存储过程。");
     }
     return InnerGetCachedParameters(dbContext.Connection, dbContext.CurrentCommand.CommandText);
 }
		/// <summary>
		/// Gets the list of News Media
		/// </summary>
		/// <param name="date">created date.</param>
		/// <returns>Returns the list of List<NewsMedia>.</returns>
      	 public List<NewsMedia> Select(DateTime date)
        {
            using (var database = new DbContext(CONNECTION_NAME))
             {
                 IQueryable<NewsMedia> query = database.Set<NewsMedia>();

                 query = AppendFilters(query,date);

                 return query.ToList();
             }

        }
		public virtual void OnBeforeSaveChanges(DbContext context)
		{
			foreach (var entry in context.GetDbStateEntries())
			{
				var type = entry.Entity.GetType();
				foreach (var complexProperty in GetComplexProperties(type))
				{
					// instantiate complex type if null
					object currentValue = complexProperty.Key.GetValue(entry.Entity, new object[0]);
					object newValue = currentValue == null ? complexProperty.Value() : null;
					OnInitializeComplexType(complexProperty.Key, entry, currentValue, newValue);
				}
			}
		}
示例#24
0
        public void Dispose()
        {
            if (Context != null)
            {
                //if (Transaction != null)
                //{
                //    Transaction.Dispose();
                //}

                //Transaction = null;
                Context.Dispose();
                Context = null;
            }
        }
        /// <summary>
        /// Submits the change through Entity Framework while logging any exceptions
        /// and produce appropriate <see cref="HttpResponseMessage"/> instances.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the operation.</returns>
        public static async Task<int> SubmitChangesAsync(DbContext context, HttpRequestMessage request, Func<DbUpdateConcurrencyException, object> getOriginalValue)
        {
            HttpConfiguration config = request.GetConfiguration();
            ITraceWriter traceWriter = config.Services.GetTraceWriter();
            try
            {
                int result = await context.SaveChangesAsync();
                return result;
            }
            catch (DbEntityValidationException ex)
            {
                string validationDescription = EntityUtils.GetValidationDescription(ex);
                string validationError = EFResources.DomainManager_ValidationError.FormatForUser(validationDescription);
                traceWriter.Debug(validationError, request, LogCategories.TableControllers);
                HttpResponseMessage invalid = request.CreateErrorResponse(HttpStatusCode.BadRequest, validationError, ex);
                throw new HttpResponseException(invalid);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                string conflictError = EFResources.DomainManager_ChangeConflict.FormatForUser(ex.Message);
                traceWriter.Info(conflictError, request, LogCategories.TableControllers);

                var content = getOriginalValue != null ? getOriginalValue(ex) : conflictError;
                HttpStatusCode statusCode = GetConflictStatusCode(request);
                HttpResponseMessage conflict = request.CreateResponse(statusCode, content);
                throw new HttpResponseException(conflict);
            }
            catch (DbUpdateException ex)
            {
                HttpResponseMessage error;
                Exception baseEx = ex.GetBaseException();
                SqlException sqlException = baseEx as SqlException;
                if (sqlException != null && sqlException.Number == SqlUniqueConstraintViolationError)
                {
                    string message = CommonResources.DomainManager_Conflict.FormatForUser(sqlException.Message);
                    error = request.CreateErrorResponse(HttpStatusCode.Conflict, message);
                    traceWriter.Info(message, request, LogCategories.TableControllers);
                }
                else
                {
                    string message = EFResources.DomainManager_InvalidOperation.FormatForUser(baseEx.Message);
                    error = request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
                    traceWriter.Error(message, request, LogCategories.TableControllers);
                }

                throw new HttpResponseException(error);
            }
        }
示例#26
0
 /// <summary>
 /// 通过EF执行sql语句获得Table
 /// </summary>
 /// <param name="db">数据库上下文</param>
 /// <param name="sql">sql语句</param>
 /// <returns></returns>
 public static DataTable SqlQueryForDataTatable(DbContext db,
 string sql)
 {
     SqlConnection conn = new System.Data.SqlClient.SqlConnection();
     conn.ConnectionString = db.Database.Connection.ConnectionString;
     if (conn.State != ConnectionState.Open) {
         conn.Open();
     }
     SqlCommand cmd = new SqlCommand();
     cmd.Connection = conn;
     cmd.CommandText = sql;
     SqlDataAdapter adapter = new SqlDataAdapter(cmd);
     DataTable table = new DataTable();
     adapter.Fill(table);
     return table;
 }
示例#27
0
 /// <summary>
 /// 根据数据库的不同调用不同的子类进行分页等操作
 /// </summary>
 /// <param name="dbContext"></param>
 /// <returns></returns>
 public static GridDataBuliderProvider Create(DbContext dbContext)
 {
     var dbprovider = dbContext.Db.DbProvider;
     if (dbprovider is Liger.Data.MsAccess.MsAccessProvider)
     {
         return new AccessGridDataBuliderProvider(dbContext);
     }
     if (dbprovider is Liger.Data.SqlServer9.SqlServer9Provider)
     {
         return new SqlServer9GridDataBuliderProvider(dbContext);
     }
     if (dbprovider is Liger.Data.SqlServer.SqlServerProvider)
     {
         return new SqlServerGridDataBuliderProvider(dbContext);
     }
     return new GridDataBuliderProvider(dbContext);
 }
		/// <summary>
		/// Update News Media Content 
		/// </summary>
		/// <param name="newsMedia">newsMedia</param>
		/// <returns>Returns the news media content</returns>
        public NewsMedia Update(NewsMedia newsMedia)
         {
             using (var database = new DbContext(CONNECTION_NAME))
              {
                 var entryMedia = database.Entry<NewsMedia>(newsMedia);

                 entryMedia.State = EntityState.Unchanged;

                 entryMedia.Property("Status").IsModified = true;

                 entryMedia.Property("Remarks").IsModified = true;

                 entryMedia.Property("IsCompleted").IsModified = true;

                 database.SaveChanges();

              }

         }
示例#29
0
 private void button1_Click_1(object sender, EventArgs e)
 {
     CodeTimer.Initialize();
     CodeTimer.Time("1", 10, new Action(
         () =>
         {
             using (DbContext dbContext = new DbContext("oracle"))
             {
                 List<TbasicPrice> list = FastDBEngine.DbHelper.FillList<TbasicPrice>(
                   "select * from TBASIC_PRICE t", null, dbContext, FastDBEngine.CommandKind.SqlTextNoParams);
                 //List<TbasicPrice> list2 = DbHelper.FillList<TbasicPrice>(
                 //    "select * from TBASIC_PRICE where PKID = :Id",
                 //     new { Id = 10000068 },
                 //     dbContext,
                 //     CommandKind.SqlTextWithParams);
                 //var query = "select * from TBASIC_PRICE where PKID =".AsCPQuery(true);
                 //query += 10000068;
                 //List<TbasicPrice> list7 = DbHelper.FillList<TbasicPrice>(query);
             };
         }));
 }
        public MigrationResult Migrate(DbContext context)
        {
            var originalTimeout = context.Database.CommandTimeout;

            try
            {
                context.Database.CommandTimeout = 600;
                context.Database.ExecuteSqlCommand(
                    TransactionalBehavior.EnsureTransaction,
                    SqlText);
            }
            finally
            {
                context.Database.CommandTimeout = originalTimeout;
            }

            return new MigrationResult
            {
                MigrationWasApplied = true,
                Log = SqlText
            };
        }