public DataStoreException([NotNull] string message, [NotNull] DbContext context, [CanBeNull] Exception innerException) : base(message, innerException) { Check.NotNull(context, "contextType"); _context = context; }
private void SetDynamicFilterParameterValues(DbCommand command, DbContext context) { if ((command == null) || (command.Parameters.Count == 0) || (context == null)) return; context.SetSqlParameters(command); }
public ConcreteDatabase( DbContext context, IRelationalDataStoreCreator dataStoreCreator, ILoggerFactory loggerFactory) : base(context, dataStoreCreator, loggerFactory) { }
protected static void AddActiveDirectoryUser(Guid userId, string name, string accountName, bool isDisabled = false, IEnumerable<KeyValuePair<string, string>> customProperties = null) { using (DbContext writeDbContext = new DbContext()) { User user = new User { Id = userId, Name = name, IsDisabled = isDisabled, }; Account account = new Account { UserId = user.Id, Name = accountName, Type = AccountType.ActiveDirectory }; user.Accounts.Add(account); if (customProperties != null) { user.CustomProperties.AddRange(customProperties.Select(c => new CustomProperty { Id = Guid.NewGuid(), Name = c.Key, Value = c.Value })); } writeDbContext.Users.Add(user); writeDbContext.SaveChanges(); } }
static void Main(string[] args) { var connectionString = ConfigurationManager.AppSettings["defaultConnection"]; using (var context = new HeroDbContext(connectionString)) { if (context.Database.Exists()) context.Database.Delete(); context.Database.Create(); } var contexts = new DbContext[] { }; foreach (var context in contexts) { var adapter = (IObjectContextAdapter)context; var script = adapter.ObjectContext.CreateDatabaseScript(); context.Database.ExecuteSqlCommand(script); context.Dispose(); } //Seed Databases using (var context = new HeroDbContext(connectionString)) { HeroDbContextInitializer.Seed(context); } }
/// <summary> /// Attempts to get the model hash calculated by Code First for the given context. /// This method will return null if the context is not being used in Code First mode. /// </summary> /// <param name = "context">The context.</param> /// <returns>The hash string.</returns> public static string TryGetModelHash(DbContext context) { //Contract.Requires(context != null); var compiledModel = context.InternalContext.CodeFirstModel; return compiledModel == null ? null : new ModelHashCalculator().Calculate(compiledModel); }
public static MensajeDto Hacer(DbContext context, MensajeDto mensajeDto) { try { context.SaveChanges(); } catch (DbUpdateException e) { var mensaje = MensajeAux(e); mensajeDto = new MensajeDto() { Error = true, MensajeDelProceso = mensaje }; } catch (DbEntityValidationException e) { var mensajeEntity = e.EntityValidationErrors.First() .ValidationErrors.First().ErrorMessage; var mensaje = MensajeAux(e); mensajeDto = new MensajeDto() { Error = true, MensajeDelProceso = mensaje + " " + mensajeEntity }; } catch (Exception e) { var mensaje = MensajeAux(e); mensajeDto = new MensajeDto() { Error = true, MensajeDelProceso = mensaje }; } return mensajeDto; }
public void Store(DbContext dbContext) { if (HttpContext.Current.Items.Contains(DataContextKey)) HttpContext.Current.Items[DataContextKey] = dbContext; else HttpContext.Current.Items.Add(DataContextKey, dbContext); }
static DbDependencyResolver() { context = new MusicCatalogueContext(); artistsRepository = new DbRepository<Artist>(context); albumsRepository = new DbRepository<Album>(context); songsRepository = new DbRepository<Song>(context); }
public EntityEntryGraphIterator( [NotNull] DbContext context, [NotNull] IStateManager stateManager) { _context = context; _stateManager = stateManager; }
private static void Main(string[] args) { var totalElementos = _objetivos.Sum(a => a.Monto); foreach (var item in _objetivos) { item.Porcentaje = Math.Round( item.Monto/(totalElementos > 0 ? totalElementos : item.Monto), 4); } var p = new DbContext(); p.Objetivos.RemoveRange(p.Objetivos.ToList()); p.SaveChanges(); if (!p.Objetivos.Any()) { p.Objetivos.AddRange(_objetivos); p.SaveChanges(); } Console.WriteLine("From Memory"); Console.WriteLine("Total Elementos {0}", totalElementos); Console.WriteLine("Total Porcentaje {0}", _objetivos.Sum(a => a.Porcentaje)); Console.WriteLine("From Db"); Console.WriteLine("Total Elementos {0}", p.Objetivos.Sum(a => a.Monto)); Console.WriteLine("Total Porcentaje {0}", p.Objetivos.Sum(a => a.Porcentaje)); Console.WriteLine("Total Porcentaje {0}", DoubleConverter.ToExactString((Double)p.Objetivos.Sum(a => a.Porcentaje))); Console.ReadKey(); }
public static void CheckRegionAllowed(IPrincipal principal,DbContext db, string regionID) { String userID = ((KawalDesaIdentity)principal.Identity).User.Id; if (userID == null) throw new ApplicationException("region is not allowed for thee"); var region = db.Set<Region>() .AsNoTracking() .Include(r => r.Parent) .Include(r => r.Parent.Parent) .Include(r => r.Parent.Parent.Parent) .Include(r => r.Parent.Parent.Parent.Parent) .First(r => r.Id == regionID); var regionIDs = new List<string>(); var current = region; while(current != null) { regionIDs.Add(current.Id); current = current.Parent; } var allowed = db.Set<UserScope>() .Any(s => s.fkUserId == userID && regionIDs.Contains(s.fkRegionId)); if (!allowed) throw new ApplicationException("region is not allowed for thee"); }
public void AddUserWithCustomProperties() { Guid userId = Guid.NewGuid(); const string userName = "******"; const string emailName = "email"; const string emailValue = "*****@*****.**"; const string addressName = "address"; const string addressValue = "street 123"; var customProperties = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(emailName, emailValue), new KeyValuePair<string, string>(addressName, addressValue) }; sut.AddUser(userId, userName, customProperties); sut.SaveChanges(); using (DbContext readContext = new DbContext()) { User user = readContext.Users.Include(u => u.CustomProperties).Single(); Assert.AreEqual(userId, user.Id); Assert.AreEqual(userName, user.Name); Assert.AreEqual(2, user.CustomProperties.Count); Assert.IsNotNull(user.CustomProperties.SingleOrDefault(c => c.Name == emailName && c.Value == emailValue)); Assert.IsNotNull(user.CustomProperties.SingleOrDefault(c => c.Name == addressName && c.Value == addressValue)); } }
public void ShouldQueryFirms() { var model = CreateModel(); using (var connection = CreateConnection()) using (var context = new DbContext(connection, model.Compile(), false)) { var firm = context.Set<Firm>() .Include(x => x.Balances) .Include(x => x.Categories) .Include(x => x.CategoryGroup) .Include(x => x.Client) .Include(x => x.Client.CategoryGroup) .Include(x => x.Client.Contacts) .Include(x => x.Territories) .OrderBy(x => x.Id) .FirstOrDefault(); Assert.That(firm, Is.Not.Null); Assert.That(firm.Name, Is.Not.Null.And.EqualTo("Firm 1")); Assert.That(firm.Balances, Is.Not.Null.And.Count.EqualTo(2)); Assert.That(firm.Categories, Is.Not.Empty.And.Count.EqualTo(1)); Assert.That(firm.CategoryGroup, Is.Not.Null); Assert.That(firm.Client, Is.Not.Null.And.Property("Name").EqualTo("Client 1")); Assert.That(firm.Client.CategoryGroup, Is.Not.Null); Assert.That(firm.Client.Contacts, Is.Not.Null.And.Count.EqualTo(3)); Assert.That(firm.Territories, Is.Not.Empty.And.Count.EqualTo(2)); } }
public DbDependencyResolver(DbContext context) { this.context = context; this.usersRepository = new DbUsersRepository(context); this.newsArticlesRepository = new DbRepository<NewsArticle>(context); this.commentsRepository = new DbRepository<Comment>(context); }
private static void Main(string[] args) { DbContext context = new DbContext("Data Source = .\\SQLEXPRESS; Initial Catalog = Test; Integrated Security = true"); var collection = context.Database.SqlQuery<Student>("SELECT * FROM Students").ToList(); foreach (var item in collection) { Console.WriteLine("{0} {1}, sex is {2}, ID is {3}", item.Name, item.LastName, item.Sex ? "male" : "female", item.Id); } TestEntities testContext = new TestEntities(); foreach (var item in testContext.Database.SqlQuery<Student>("SELECT * FROM Students")) { Console.WriteLine(item.Name); } foreach (var item in testContext.Groups) { Console.WriteLine(item.Motto + ":"); foreach (var student in item.Students) { Console.WriteLine("{0} {1} ({2})", student.Name, student.LastName, item.Head.Name); } } }
/// <copydocfrom cref="IDbContextProvider.Close" /> public void Close() { lock (syncLock) { context = null; } }
internal void RegisterDbContext(DbContext dbContext) { if (!_dbContexts.Exists(dbCtx => dbCtx.Equals(dbContext))) { _dbContexts.Add(dbContext); } }
public void ApplyUniqueConstraints(DbContext context) { var modelTypes = from dbContextProperties in context.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public) let propertyTypeGenericArguments = dbContextProperties.PropertyType.GetGenericArguments() where propertyTypeGenericArguments.Count() == 1 select propertyTypeGenericArguments.Single(); var modelsWithUniqueProperties = from modelType in modelTypes from property in modelType.GetProperties(BindingFlags.Instance | BindingFlags.Public) from uniqueAttribute in property.GetCustomAttributes(true).OfType<UniqueAttribute>() let propertyName = property.Name group propertyName by modelType into uniquePropertiesByModel select new { Model = uniquePropertiesByModel.Key, Properties = (IEnumerable<string>) uniquePropertiesByModel }; foreach (var model in modelsWithUniqueProperties) { foreach (var property in model.Properties) { string tableName = GetTableName(model.Model); string query = string.Format(UniqueConstraintQuery, tableName, property); context.Database.ExecuteSqlCommand(query); } } }
protected static void AddTestData(DbContext context) { var address1 = new Address { Street = "3 Dragons Way", City = "Meereen" }; var address2 = new Address { Street = "42 Castle Black", City = "The Wall" }; var address3 = new Address { Street = "House of Black and White", City = "Braavos" }; context.Set<Person>().AddRange( new Person { Name = "Daenerys Targaryen", Address = address1 }, new Person { Name = "John Snow", Address = address2 }, new Person { Name = "Arya Stark", Address = address3 }, new Person { Name = "Harry Strickland" }); context.Set<Address>().AddRange(address1, address2, address3); var address21 = new Address2 { Id = "1", Street = "3 Dragons Way", City = "Meereen" }; var address22 = new Address2 { Id = "2", Street = "42 Castle Black", City = "The Wall" }; var address23 = new Address2 { Id = "3", Street = "House of Black and White", City = "Braavos" }; context.Set<Person2>().AddRange( new Person2 { Name = "Daenerys Targaryen", Address = address21 }, new Person2 { Name = "John Snow", Address = address22 }, new Person2 { Name = "Arya Stark", Address = address23 }); context.Set<Address2>().AddRange(address21, address22, address23); context.SaveChanges(); }
private static void AppendDescriptionUsingContext(DbContext context, StringBuilder builder, EntityType type, ActionType aType, object entity) { string additionalInfo = string.Empty; string identity = string.Empty; var enrty = context.Entry(entity); var prop = enrty.Entity.GetType() .GetProperties() .FirstOrDefault(c => c.GetCustomAttributes(typeof(KeyAttribute), true).FirstOrDefault() != null); var name = enrty.Entity.GetType().GetProperties().FirstOrDefault(c => c.Name.Contains("Name")); identity = CreateIdentityString(entity, prop, identity, name); if (aType == ActionType.Updating) { additionalInfo = string.Format("Были изменены следующие поля: {0}", string.Join(",", enrty.CurrentValues.PropertyNames)); } if (aType != ActionType.Import || aType != ActionType.Export) { builder.Append(string.Format("Сущность \"{0}\" {1} была {2}.{3}", type.GetEntityTypeName(), identity, aType.GetActionTypeName(), additionalInfo)); } }
public void CheckValue(DbContext ctx, object actual) { var propertyType = Accessor.MemberType; var objectContext = ((IObjectContextAdapter)ctx).ObjectContext; var entitySet = objectContext.GetEntitySet(propertyType); var keyMembers = entitySet.ElementType.KeyMembers; ctx.Entry(actual).Reference(Accessor.Name).Load(); var actualEntity = Accessor.GetValue(actual); if (actualEntity == null) { throw new AssertionException(ExpectedEntity.Dump(), "NULL"); } foreach (var keyMember in keyMembers) { var accessor = new PropertyAccessor(propertyType.GetProperty(keyMember.Name)); var actualKeyValue = accessor.GetValue(actualEntity); var expectedKeyValue = accessor.GetValue(ExpectedEntity); if (!expectedKeyValue.Equals(actualKeyValue)) { throw new AssertionException(ExpectedEntity.Dump(), actualEntity.Dump()); } } }
protected virtual void FindSets(ModelBuilder modelBuilder, DbContext context) { foreach (var setInfo in SetFinder.FindSets(context)) { modelBuilder.Entity(setInfo.EntityType); } }
public void Registrar(DbContext dbContext) { RegistrarModulo(); RegistrarOperaciones(); dbContext.Set<Formulario>().Add(_moduloFormulario); }
public UserService(DbContext context, IRepository<User> users, IRepository<Message, int> messages) { this.users = users; this.messages = messages; this.userManager = new UserManager<User>(new UserStore<User>(context)); this.roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); }
public EntityFrameworkExternalDataSource(DbContext dbContext) { _dbContext = dbContext; SetOptionsForDbContext(_dbContext); _efManager = new EFManager(dbContext); _efManager.ReloadDbEntries(); }
private static void ExecuteResources(DbContext context, IEnumerable<string> resources) { foreach (var resource in resources) { SqlBatchExecutor.ExecuteResourceStreamFromExecutingAssembly(context, resource); } }
public void GuardClause_all() { Assert.Throws<ArgumentNullException>(() => { var value = new DbContext(null, null); }); }
public DbContextWrapper(DbContext context) { Context = context; objectContext = ((IObjectContextAdapter) context).ObjectContext; objectContext.ObjectMaterialized += ObjectMaterializedHandler; }
public TransactionDataRepository(DbContext context) : base(context) { _context = context; }
protected Repository(DbContext context) { this.context = context; }
private DbContext InitializeMemory() { context = ContextFactory.GetNewContextForTesting(ContextType.MEMORY); return(context); }
public GenericRepository(DbContext context) { _context = context; }
public Repository(DbContext context) { this.context = context; this.set = context.Set <T>(); }
public BusinessHoursRepository(DbContext dbContext) : base(dbContext) { }
/// <summary> /// Destroys an object /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="dbCtx"></param> /// <returns></returns> public static async Task <T> DestroyAsync <T>(this T obj, DbContext dbCtx) where T : Base { return(await obj.DestroyAsync <T>(dbCtx, obj.Uuid)); }
/// <summary> /// ctor /// </summary> /// <param name="context">Контекст БД</param> public TransactionRepository(DbContext context) : base(context) { }
public ExaminationRepository(DbContext context) : base(context) { }
protected Repository(DbContext context) { _context = context; }
/// <summary> /// 一个业务中经常涉及到对多张操作,我们希望链接一次数据库,完成对张表数据的操作。提高性能。 工作单元模式。 /// </summary> /// <returns></returns> public bool SaveChanged() { return(DbContext.SaveChanges() > 0); }
public ReferralRepository(DbContext dbContext) : base(dbContext) { }
public TestNpgsqlRetryingExecutionStrategy(DbContext context, TimeSpan maxDelay) : base(context, DefaultMaxRetryCount, maxDelay, AdditionalSqlStates) { }
public void Dispose() { DbContext.Dispose(); }
public UserRepository(DbContext context) : base(context) { }
public SoftDeletableRepository(DbContext context) : base(context) { }
/// <summary> /// 构建一个只读的常用查询辅助类 /// </summary> /// <param name="dbcontext"></param> /// <remarks> /// 1.不提供add,update,delete等方法 /// 2.不提供状态跟踪,即默认AsNoTracking /// </remarks> public ReadOnlyQueryable(DbContext dbcontext, IQueryable <TSource> source) { this.dbcontext = dbcontext; this.source = source; }
public RepositoryBase(DbContext ctx) { dbcontext = ctx; }
/// <summary>Adds audit entries before the save changes has been executed.</summary> /// <param name="context">The context.</param> public void PreSaveChanges(DbContext context) { PreSaveChanges(this, context); }
public UnitOfWorkBase(DbContext _db) { db = _db; }
public ReviewRepository(DbContext context) : base(context) { }
public TrainingRepository(DbContext context) : base(context) { }
public Repository(DbContext context) { _context = context; _entities = context.Set <TEntity>(); }
GetTableNamesInOrderForWipe //#A (this DbContext context, int maxDepth = 10, params Type[] excludeTypes) //#B { var allEntities = context.Model .GetEntityTypes() .Where(x => !excludeTypes.Contains(x.ClrType)) .ToList(); //#C ThrowExceptionIfCannotWipeSelfRef(allEntities); //#D var principalsDict = allEntities //#E .SelectMany(x => x.GetForeignKeys() .Select(y => y.PrincipalEntityType)).Distinct() .ToDictionary(k => k, v => //#F v.GetForeignKeys() .Where(y => y.PrincipalEntityType != v) //#G .Select(y => y.PrincipalEntityType).ToList()); //#H var result = allEntities //#I .Where(x => !principalsDict.ContainsKey(x)) //#I .ToList(); //#I /************************************************************************ #A This method looks at the relationships and returns the tables names in the right order to wipe all their rows without incurring a foreign key delete constraint #B You can exclude entity classes that you need to handle yourself, for instance - any references that only contain circular references #C This gets the IEntityType for all the entities, other than those that were excluded. This contains the information on how each table is built, with its relationships #D This contains a check for the hierarchical (entity that references itself) case where an entity refers to itself - if the delete behavior of this foreign key is set to restrict then you cannot simply delete all the rows in one go #E I extract all the principal entities from the entities we are considering ... #F ... And put them in a dictionary, with the IEntityType being the key #G ... I remove any self reference links as these are automatically handled #H ... And the PrincipalEntityType being the value #I I start the list of entities to delete by putting all the dependant entities first, as I must delete the rows in these tables first, and the order doesn't matter ************************************************************/ var reversePrincipals = new List <IEntityType>(); //#A int depth = 0; //#B while (principalsDict.Keys.Any()) //#C { foreach (var principalNoLinks in principalsDict .Where(x => !x.Value.Any()).ToList()) //#D { reversePrincipals.Add(principalNoLinks.Key); //#E principalsDict .Remove(principalNoLinks.Key); //#F foreach (var removeLink in principalsDict.Where(x => x.Value.Contains(principalNoLinks.Key))) //#G { removeLink.Value .Remove(principalNoLinks.Key); //#H } } if (++depth >= maxDepth) //#I { ThrowExceptionMaxDepthReached( principalsDict.Keys.ToList(), depth); } } reversePrincipals.Reverse(); //#J result.AddRange(reversePrincipals); //#K return(result.Select(FormTableNameWithSchema)); //#L }
public Repository(DbContext context) { this._context = context; }
public RoleRepository(DbContext context) : base(context) { }
public PaymentRepository(DbContext context) : base(context) { }
public HelperRepository(DbContext context) { _context = context; }
public MissingPipe(DbContext dbContext, IPipe <SagaConsumeContext <TSaga, TMessage> > next) { _dbContext = dbContext; _next = next; }
public MemberRepository(DbContext context) : base(context) { }
/// <copydocfrom cref="IDbContextProvider.CurrentContext" /> public DbContext CurrentContext() { lock (syncLock) { return context ?? (context = func()); } }