// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationDbContext dbContext, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseGlobalExceptionMiddleware(); app.UseHttpsRedirection(); app.UseRouting(); app.UseOpenApi(); app.UseSwaggerUi3(); app.UseReDoc(configuration => configuration.Path = string.Empty); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub <ServiceHub>("/ServiceHub"); }); DbContextExtensions.Seed(dbContext, serviceProvider); }
public void TableNameForGitHubIssue17ShouldPass() { var sql = @"SELECT [Extent1].[Id] AS [Id], [Extent1].[Identifier] AS [Identifier], [Extent1].[Name] AS [Name], [Extent1].[Latitude] AS [Latitude], [Extent1].[Longitude] AS [Longitude], [Extent1].[FIR] AS [FIR], [Extent1].[UIR] AS [UIR], [Extent1].[ICAO] AS [ICAO], [Extent1].[MagneticVariation] AS [MagneticVariation], [Extent1].[Frequency] AS [Frequency], [Extent1].[CountryName] AS [CountryName], [Extent1].[CountryId] AS [CountryId], [Extent1].[StateId] AS [StateId], [Extent1].[CityId] AS [CityId], [Extent1].[IsActive] AS [IsActive] FROM [dbo].[Points] AS [Extent1] WHERE ([Extent1].[IsActive] = @DynamicFilterParam_000001) OR (@DynamicFilterParam_000002 IS NOT NULL)"; var tableName = DbContextExtensions.ParseTableName(sql); Assert.AreEqual("Points", tableName.Name); Assert.AreEqual("dbo", tableName.Schema); }
public void TestInsertSql() { var dut = DbContextExtensions.GetSqlInsertString("lala", new string[] {"a", "b", "c"}, 5); Assert.That(dut.Contains("@p0")); Assert.That(dut.Contains("@p14")); Assert.That(dut.Count(x => x == '@'), Is.EqualTo(15)); Console.WriteLine(dut); }
public void CreateTriggerSession_ValidDbContext_CreatesNewSession() { var context = new TestDbContext(); var triggerSession = DbContextExtensions.CreateTriggerSession(context); Assert.NotNull(triggerSession); Assert.NotNull(context.GetService <ITriggerService>()?.Current); }
/// <summary> /// 使用附带新值的实体信息更新指定实体属性的值(把原来的记录都删除,再添加一条) /// </summary> /// <param name="propertyExpression">属性表达式</param> /// <param name="isSave">是否执行保存</param> /// <param name="entity">附带新值的实体信息,必须包含主键</param> /// <returns>操作影响的行数</returns> /*public int Update(Expression<Func<TEntity, object>> propertyExpression, TEntity entity, bool isSave = true) * { * //throw new NotSupportedException("上下文公用,不支持按需更新功能。"); * PublicHelper.CheckArgument(propertyExpression, "propertyExpression"); * PublicHelper.CheckArgument(entity, "entity"); * EFContext.RegisterModified<TEntity>(propertyExpression, entity); * if (isSave) * { * var dbSet = EFContext.Set<TEntity>(); * dbSet.Local.Clear(); * var entry = EFContext.DbContext.Entry(entity); * return EFContext.Commit(false); * } * return 0; * }*/ public int Update(Expression <Func <TEntity, object> > propertyExpression, params TEntity[] entities) { PublicHelper.CheckArgument(propertyExpression, "propertyExpression"); PublicHelper.CheckArgument(entities, "entity"); DbContextExtensions.Update <TEntity>(this.EFContext.DbContext, propertyExpression, entities); return(DbContextExtensions.SaveChanges(this.EFContext.DbContext, false)); //EFContext.Update<TEntity>(propertyExpression, entities); //return EFContext.Commit(false); }
public void TestUpdateSql() { var dut = DbContextExtensions.GetSqlUpdateString("lala", new [] { "id" }, new [] { "a", "b", "c" }, 1); Assert.That(dut.Contains("@p0")); Assert.That(dut.Contains("@p2")); Assert.That(dut.Contains("@k0")); Assert.That(dut.Count(x => x == '@'), Is.EqualTo(4)); Console.WriteLine(dut); }
public int ExecuteByProc(string procName, params DbParameter[] dbParameter) { if (dbTransaction == null) { return(dbcontext.Database.ExecuteSqlCommand(DbContextExtensions.BuilderProc(procName, dbParameter), dbParameter)); } else { dbcontext.Database.ExecuteSqlCommand(DbContextExtensions.BuilderProc(procName, dbParameter), dbParameter); return(dbTransaction == null?this.Commit() : 0); } }
/// <summary> /// 执行存储过程 /// </summary> /// <param name="procName"></param> /// <returns></returns> public int ExecuteByProc(string procName) { if (DbTransaction == null) { return(Dbcontext.Database.ExecuteSqlCommand(DbContextExtensions.BuilderProc(procName))); } else { Dbcontext.Database.ExecuteSqlCommand(DbContextExtensions.BuilderProc(procName)); return(DbTransaction == null?this.Commit() : 0); } }
public int Delete <T>(object propertyValue, string propertyName) where T : class { EntitySet entitySet = DbContextExtensions.GetEntitySet <T>(dbcontext); if (entitySet != null) { string tableName = entitySet.MetadataProperties.Contains("Table") && entitySet.MetadataProperties["Table"].Value != null ? entitySet.MetadataProperties["Table"].Value.ToString() : entitySet.Name; return(this.ExecuteBySql(DbContextExtensions.DeleteSql(tableName, propertyName, propertyValue))); } return(-1); }
public int Delete <T>(object[] keyValue) where T : class { EntitySet entitySet = DbContextExtensions.GetEntitySet <T>(dbcontext); if (entitySet != null) { string tableName = entitySet.MetadataProperties.Contains("Table") && entitySet.MetadataProperties["Table"].Value != null ? entitySet.MetadataProperties["Table"].Value.ToString() : entitySet.Name; string keyFlied = entitySet.ElementType.KeyMembers[0].Name; return(this.ExecuteBySql(DbContextExtensions.DeleteSql(tableName, keyFlied, keyValue))); } return(-1); }
public override void AddOrUpdate(SalesOrderMaster entity) { if (DbContextExtensions.IsTransient(_context, entity)) { _context.Set <SalesOrderMaster>().Add(entity); _context.SaveChanges(); } else { _context.Set <SalesOrderMaster>().Attach(entity); _context.Entry(entity).State = EntityState.Modified; _context.SaveChanges(); } }
public override void AddOrUpdate(QuotationMaster entity) { if (DbContextExtensions.IsTransient(_context, entity)) { _context.Set <QuotationMaster>().Add(entity); _context.SaveChanges(); } else { _context.Set <QuotationMaster>().Attach(entity); _context.Entry(entity).State = EntityState.Detached; _context.SaveChanges(); } }
public static TodoAppContext GetTodoesDbContext(string dbName) { // Create options for DbContext instance var options = new DbContextOptionsBuilder <TodoAppContext>() .UseInMemoryDatabase(databaseName: dbName) .Options; // Create instance of DbContext var dbContext = new TodoAppContext(options); // Add entities in memory DbContextExtensions.Seed(dbContext); return(dbContext); }
public void ParameterTest(int columns, int rows, int expectedParameterCount, int expectedBatchSize, int expectedRemainderBatchsize) { DbContextOptionsBuilder<MyContext> opt = new DbContextOptionsBuilder<MyContext>(); opt.UseSqlite("Filename=testparameter.sqlite"); var context = new MyContext(opt.Options); var (dbParameters, batchSize, remainder) = DbContextExtensions.GetInsertParametersAndBatchSize(context, columns, rows); Assert.That(dbParameters.Length, Is.EqualTo(expectedParameterCount)); Assert.That(batchSize, Is.EqualTo(expectedBatchSize)); Assert.That(remainder, Is.EqualTo(expectedRemainderBatchsize)); Assert.That(dbParameters[0].ParameterName, Is.EqualTo("p0")); Assert.That(dbParameters[dbParameters.Length-1].ParameterName, Is.EqualTo("p"+(dbParameters.Length-1))); }
/// <summary> /// Update entities /// </summary> /// <param name="entities">Entities</param> public virtual void Update(IEnumerable <T> entities) { try { if (entities == null) { throw new ArgumentNullException("entities"); } DbContextExtensions.BulkUpdate(_context as DbContext, entities); //this._context.SaveChanges(); } catch (DbEntityValidationException dbEx) { throw new Exception(GetFullErrorText(dbEx), dbEx); } }
public int Delete <T>(object[] keyValue) where T : class { EntitySet entitySet = DbContextExtensions.GetEntitySet <T>(dbcontext); if (entitySet != null) { string schema = (entitySet.MetadataProperties.Contains("Schema") && entitySet.MetadataProperties["Schema"].Value != null) ? entitySet.MetadataProperties["Schema"].Value.ToString() : ""; string tableName = (entitySet.MetadataProperties.Contains("Table") && entitySet.MetadataProperties["Table"].Value != null) ? entitySet.MetadataProperties["Table"].Value.ToString() : entitySet.Name; string fullName = string.IsNullOrEmpty(schema) ? tableName : (schema + "." + tableName); string keyFlied = entitySet.ElementType.KeyMembers[0].Name; return(this.ExecuteBySql(DbContextExtensions.DeleteSql(fullName, keyFlied, keyValue))); } return(-1); }
/// <summary> /// Delete entities /// </summary> /// <param name="entities">Entities</param> public virtual void Delete(IEnumerable <T> entities) { try { if (entities == null) { throw new ArgumentNullException("entities"); } //foreach (var entity in entities) // this.Entities.Remove(entity); DbContextExtensions.BulkDelete(_context as DbContext, entities); //this._context.SaveChanges(); } catch (DbEntityValidationException dbEx) { throw new Exception(GetFullErrorText(dbEx), dbEx); } }
protected List <MappedProperty> GetPropertiesHierarchy(Type propertyType, List <string> parentPropertyNames) { if (parentPropertyNames.Count == 2) { throw new NotImplementedException("More than 1 level of Entity framework owned entities is not supported."); } List <MappedProperty> list = new List <MappedProperty>(); //Include all primitive properties BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance; PropertyInfo[] allEntityProperties = propertyType.GetProperties(bindingFlags); List <PropertyInfo> primitiveProperties = allEntityProperties.Where( p => { Type underlying = Nullable.GetUnderlyingType(p.PropertyType); Type property = underlying ?? p.PropertyType; return(property.IsValueType == true || property.IsPrimitive || property == typeof(string)); }) .ToList(); //Exclude ignored properties IEntityType efEntityType = null; if (propertyType == _rootEntityType) { efEntityType = _efRootEntityType; } else { string propertyName = parentPropertyNames[0]; efEntityType = _context.GetOwnedProperty(_efRootEntityType, propertyName); } List <string> efMappedProperties = efEntityType.GetProperties() .Select(x => x.Name) .ToList(); primitiveProperties = primitiveProperties .Where(x => efMappedProperties.Contains(x.Name)) .ToList(); //Return all the rest properties foreach (PropertyInfo supportedProp in primitiveProperties) { List <string> namesHierarchy = parentPropertyNames.ToList(); namesHierarchy.Add(supportedProp.Name); string efDefaultName = ReflectionUtility.ConcatenateEfPropertyName(namesHierarchy); IProperty property = DbContextExtensions.GetPropertyMapping(_context, _rootEntityType, efDefaultName); list.Add(new MappedProperty { PropertyInfo = supportedProp, EfDefaultName = efDefaultName, EfMappedName = property.GetColumnName(), ConfiguredSqlType = property.GetColumnType() }); } //Add complex properties List <MappedProperty> complexProperties = GetComplexProperties(allEntityProperties, parentPropertyNames); list.AddRange(complexProperties); return(list); }
public void ThrowsArgumentNullExceptionForNullDbContext() { ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => DbContextExtensions.GetFullEntitySetName(null, typeof(DbContextProduct))); }
public void ThrowsArgumentNullExceptionForNullDbContext() { ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => DbContextExtensions.SetTransactionLevel(null, IsolationLevel.ReadUncommitted)); }
public void ThrowsArgumentNullExceptionForNullContext() { ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => DbContextExtensions.GetTableName((ObjectContext)null, typeof(DbContextProduct))); }
public void ThrowsArgumentNullExceptionForNullDbContext() { ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => DbContextExtensions.GetObjectContext(null)); }
private void UpdateTimeTracker() { var dbContextExtension = new DbContextExtensions(_httpContext, ChangeTracker); dbContextExtension.UpdateTimeTracker(); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { ConfiguraProvedor(optionsBuilder); optionsBuilder.UseLoggerFactory(DbContextExtensions.GetProvider()); base.OnConfiguring(optionsBuilder); }
public int SaveChange() { return(DbContextExtensions.SaveChanges(this, RefreshConflict.MergeClientAndStore)); }
protected List <MappedProperty> GetPropertiesHierarchy(Type rootType, Type propertyType, List <string> parentPropertyNames) { List <MappedProperty> list = new List <MappedProperty>(); BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance; PropertyInfo[] allEntityProperties = propertyType.GetProperties(bindingFlags); List <PropertyInfo> mappedProperties = allEntityProperties.Where( p => { Type underlined = Nullable.GetUnderlyingType(p.PropertyType); Type property = underlined ?? p.PropertyType; return(property.IsValueType == true || property.IsPrimitive || property == typeof(string)); }) .ToList(); foreach (PropertyInfo supportedProp in mappedProperties) { List <string> namesHierarchy = parentPropertyNames.ToList(); namesHierarchy.Add(supportedProp.Name); string efDefaultName = ReflectionUtility.ConcatenateEfPropertyName(namesHierarchy); string efMappedName = DbContextExtensions.GetColumnName(_context, rootType, efDefaultName); list.Add(new MappedProperty { PropertyInfo = supportedProp, EfDefaultName = efDefaultName, EfMappedName = efMappedName }); } List <PropertyInfo> complexProperties = allEntityProperties.Where( p => p.PropertyType != typeof(string) && p.PropertyType.IsClass) .ToList(); //Exclude navigation properties //ICollection properties are excluded already as interfaces and not classes. //Here we exclude virtual properties that are not ICollection, by checking if they are virtual. complexProperties = complexProperties .Where(x => x.GetAccessors()[0].IsVirtual == false) .ToList(); foreach (PropertyInfo complexProp in complexProperties) { List <string> namesHierarchy = parentPropertyNames.ToList(); namesHierarchy.Add(complexProp.Name); List <MappedProperty> childProperties = GetPropertiesHierarchy(rootType, complexProp.PropertyType, namesHierarchy); if (childProperties.Count > 0) { list.Add(new MappedProperty { PropertyInfo = complexProp, ChildProperties = childProperties }); } } return(list); }
public void Update <TEntity>(Expression <Func <TEntity, object> > propertyExpression, params TEntity[] entities) where TEntity : class { DbContextExtensions.Update <TEntity>(Context, propertyExpression, entities); IsCommitted = false; }
//public void BulkInsert2(IList<BaseEntity<TKey>> entities) //{ // this.BulkInsert<> //} public void BulkSaveChange() { DbContextExtensions.BulkSaveChanges(this); }
public virtual void AddOrUpdate(T entity) { DbContextExtensions.AddOrUpdate <T>(_context, entity); }
static void Main(string[] args) { DataSet ds_1 = new DataSet(); Dictionary <int, Object> AllTestCases = new Dictionary <int, object>(); Dictionary <string, string> TestCase1 = new Dictionary <string, string>(); TestCase1.Add("ID", "123"); Dictionary <string, string> TestCase2 = new Dictionary <string, string>(); TestCase2.Add("ID", "123"); AllTestCases.Add(1, TestCase1); AllTestCases.Add(2, TestCase2); for (int item = 1; item <= AllTestCases.Count; item++) { Console.WriteLine("\n"); Console.WriteLine("Testcase number " + (item)); Console.WriteLine("\n"); ds_1 = DbContextExtensions.ExecuteStoredProcedure("GetSampleData_1", (Dictionary <string, string>)AllTestCases[item]); DataSet ds_2 = new DataSet(); ds_2 = DbContextExtensions.ExecuteStoredProcedure("GetSampleData_2", (Dictionary <string, string>)AllTestCases[item]); #region Check if any dataset null Console.WriteLine("*******Check if any dataset null*******"); if (ds_1 == null || ds_2 == null) { Console.WriteLine("One of the returned dataset is null"); return; } if (ds_1.Tables.Count == 0 || ds_2.Tables.Count == 0) { Console.WriteLine("One of the returned dataset is null"); return; } #endregion #region Compare Tables Count between Datasets Console.WriteLine("*******Compare Tables Count between Datasets*******"); if (ds_1.Tables.Count != ds_2.Tables.Count) { Console.WriteLine("There is a mismatch in tables recieved between datasets , 1st DS Count = {0} : 2nd DS Count = {1} " + ds_1.Tables.Count, ds_2.Tables.Count); return; } #endregion #region Compare Table Names between Datasets Console.WriteLine("*******Compare Table Names between Datasets*******"); List <string> ds_1_TableNames = new List <string>(); List <string> ds_2_TableNames = new List <string>(); //Load list with ds_1 tables foreach (DataTable table in ds_1.Tables) { ds_1_TableNames.Add(table.TableName); } //Load list with ds_2 tables foreach (DataTable table in ds_2.Tables) { ds_2_TableNames.Add(table.TableName); } for (int i = 0; i < ds_1_TableNames.Count; i++) { if (ds_1_TableNames[i] != ds_2_TableNames[i]) { Console.WriteLine("There is a mismatch in table names b/w tables , 1st Table = {0} : 2nd Table = {1} " + ds_1_TableNames[i], ds_2_TableNames[i]); return; } } #endregion #region Compare each table Columns Console.WriteLine("*******Compare each table Columns*******"); DataTable dt_1, dt_2; for (int i = 0; i < ds_1_TableNames.Count; i++) { dt_1 = ds_1.Tables[i]; dt_2 = ds_2.Tables[i]; CompareRows(dt_1, dt_2); } #endregion } Console.ReadLine(); }