public EntityError Resolve(EntityManager em) { IsServerError = true; try { EntityType entityType = null; if (EntityTypeName != null) { var stName = TypeNameInfo.FromClrTypeName(EntityTypeName).ToClient(em.MetadataStore).StructuralTypeName; entityType = em.MetadataStore.GetEntityType(stName); var ek = new EntityKey(entityType, KeyValues); Entity = em.GetEntityByKey(ek); } if (entityType != null) { if (PropertyName != null) { Property = entityType.Properties.FirstOrDefault(p => p.NameOnServer == PropertyName); if (Property != null) { PropertyName = Property.Name; } } var vc = new ValidationContext(this.Entity); vc.Property = Property; var veKey = (ErrorName ?? ErrorMessage) + (PropertyName ?? ""); var ve = new ValidationError(null, vc, ErrorMessage, veKey); ve.IsServerError = true; this.Entity.EntityAspect.ValidationErrors.Add(ve); } } catch (Exception e) { ErrorMessage = ( ErrorMessage ?? "") + ": Unable to Resolve this error: " + e.Message; } return this; }
/// <summary> /// Envia correo de usuario nuevo. /// </summary> /// <param name="USR_USERNAME"></param> /// <param name="USR_PASSWORD"></param> /// <param name="Configuracion"></param> public static void EnviarCorreoUsuarioNuevo(string USR_USERNAME, string USR_PASSWORD, XmlDocument Configuracion) { try { UsuarioLogic usuariologica = new UsuarioLogic(); usuario user = usuariologica.GetUsuario(USR_USERNAME); string mailto = user.USR_CORREO; string nombre = user.USR_NOMBRE + " " + user.USR_APELLIDO; string subject = ""; string message = ""; using (var db = new colinasEntities()) { EntityKey k = new EntityKey("colinasEntities.plantillas_notificaciones", "PLANTILLAS_LLAVE", "USUARIONUEVO"); var pl = db.GetObjectByKey(k); plantilla_notificacion plantilla = (plantilla_notificacion)pl; subject = plantilla.PLANTILLAS_ASUNTO; message = plantilla.PLANTILLAS_MENSAJE; } message = message.Replace("{NOMBRE}", nombre); message = message.Replace("{USUARIO}", USR_USERNAME); message = message.Replace("{CONTRASEÑA}", USR_PASSWORD); EnviarCorreo(mailto, subject, message, Configuracion); } catch (Exception ex) { log.Fatal("Error fatal al enviar correo de usuario nuevo.", ex); throw; } }
public void ApplyChanges(MappingSet mappingSet, EntityKey key) { // Create new Component var component = existingSpecToUse.CreateImplementedComponentFor(key.Parent, newComponentName); // Set mapped column on the new Component's properties. foreach(var pair in propertyMappings) { var newProperty = component.GetProperty(pair.Key); var oldProperty = key.Properties.FirstOrDefault(p => p.Name == pair.Value); if(oldProperty == null) { // Something went horribly wrong. We have a Property that has been mapped, // but it doesn't actually exist. I am chosing to ignore this here, but log it. log.ErrorFormat("Property {0} was mapped in the ConvertKeyToComponent wizard, but doesn't actually exist in the model.", pair.Value); continue; } newProperty.SetMappedColumn(oldProperty.MappedColumn()); } // Delete existing properties if needed. if(deleteExistingProperties) { foreach(var property in key.Properties.ToList()) { property.DeleteSelf(); } } key.Component = component; }
public EntityRecord LookupByPrimaryKey(EntityKey primaryKey) { EntityRecord rec; if (RecordsByPrimaryKey.TryGetValue(primaryKey, out rec)) return rec; return null; }
public void AddOrUpdate(System.Globalization.CultureInfo culture, EntityKey key, IEnumerable<PropertyTranslation> propertyTranslations) { using (var db = new MultilingualDbContext(InstanceName)) { var entry = db.Translations.Find(GetUnderlyingEntityKey(culture.Name, key)); if (entry == null) { entry = new EntityTranslationDbEntry { Culture = culture.Name, EntityType = key.EntityType.Name, EntityKey = key.Value.ToString() }; entry.Properties = JsonConvert.SerializeObject(propertyTranslations); db.Translations.Add(entry); } else { entry.Properties = JsonConvert.SerializeObject(propertyTranslations); entry.IsOutOfDate = false; } db.SaveChanges(); Event.Raise(new TranslationUpdated(key, propertyTranslations, culture), GetInstance()); } }
static void Main(string[] args) { using (VS2010Entities ie = new VS2010Entities()) { EntityKey ek = new EntityKey("VS2010Entities.PESSOA", "COD_PESSOA", 8); PESSOA p = (PESSOA)ie.GetObjectByKey(ek); if (p != null) p.NOME_PESSOA = "EMA FROST"; foreach (var item in ie.PESSOA) { Console.WriteLine(item.NOME_PESSOA); } Console.WriteLine("------------------------"); ie.SaveChanges(); foreach (var item in ie.PESSOA) { Console.WriteLine(item.NOME_PESSOA); } Console.ReadKey(); } }
public BriefView(int id, bool w) { obj = new TravelDAL.Tour(); using (var context = new TravelDBEntities()) { EntityKey key = new EntityKey("TravelDBEntities.Tour", "IDTour", id); obj = (TravelDAL.Tour)context.GetObjectByKey(key); if (obj != null) { tourname = obj.Name; addinfo = obj.AdditionalInfo; if (addinfo.Length > 120) addinfo = addinfo.Substring(0, 120); addinfo += "..."; minprice = obj.MinimalPrice.ToString(); avgprice = obj.AveragePrice.ToString(); rating = obj.AverageMark.ToString(); wide = w; foreach (TravelDAL.Country m in obj.Country) { countrynames += m.Name; countrynames += " "; } } } }
/// <summary> /// Removes the Category by ID. /// </summary> /// <param name="categoryID">The category ID.</param> public static void RemoveByID(int categoryID) { object categoryForDeletion; EntityKey categoryKey = new EntityKey("WebCalendarEntities.Categories", "ID", categoryID); if (db.TryGetObjectByKey(categoryKey, out categoryForDeletion)) { try { db.DeleteObject(categoryForDeletion); db.SaveChanges(); } catch (OptimisticConcurrencyException ex) { throw new InvalidOperationException(string.Format( "The Category with an ID of '{0}' could not be deleted.\n" + "Make sure that any related objects are already deleted.\n", categoryKey.EntityKeyValues[0].Value), ex); } } else { throw new InvalidOperationException(string.Format( "The Category with an ID of '{0}' could not be found.\n" + "Make sure that Category exists.\n", categoryKey.EntityKeyValues[0].Value)); } }
/// <summary> /// Creates an EntityKey that represents a Conceptual Null /// </summary> /// <param name="originalKey">An EntityKey representing the existing FK values that could not be nulled</param> /// <returns>EntityKey marked as a conceptual null with the FK values from the original key</returns> public static EntityKey CreateConceptualNullKey(EntityKey originalKey) { Debug.Assert(originalKey != null, "Original key can not be null"); //Conceptual nulls have special entity set name and a copy of the previous values EntityKey nullKey = new EntityKey(s_NullForeignKey, originalKey.EntityKeyValues); return nullKey; }
/// <summary> /// Creates an EntityKey that represents a Conceptual Null /// </summary> /// <param name="originalKey"> An EntityKey representing the existing FK values that could not be nulled </param> /// <returns> EntityKey marked as a conceptual null with the FK values from the original key </returns> public static EntityKey CreateConceptualNullKey(EntityKey originalKey) { DebugCheck.NotNull(originalKey); //Conceptual nulls have special entity set name and a copy of the previous values var nullKey = new EntityKey(s_NullForeignKey, originalKey.EntityKeyValues); return nullKey; }
public void AddEntityToIndex(EntityKey entityKey, Document doc) { // when creating a projection index, the entity key should not be passed Debug.Assert(entityKey == null); // adding document to index this._index.AddEntity(doc); }
/// <summary> /// Private extension method for ObjectStateManager class /// Dump all tracking info to a string /// </summary> /// <param name="manager">ObjectStateManager</param> /// <param name="objectStateEntries">Collection of ObjectStateEntries. If null, then all entities will be displayed</param> /// <param name="entityKey">EntityKey of given entity. If null, then all entities will be displayed</param> /// <param name="asHtml">Output string as HTML</param> /// <returns>String with tracking info about entries</returns> private static string Dump( ObjectStateManager manager, IEnumerable<ObjectStateEntry> objectStateEntries, EntityKey entityKey, bool asHtml) { StringBuilder dump = new StringBuilder(); if (entityKey != null) { objectStateEntries = new List<ObjectStateEntry>(); (objectStateEntries as List<ObjectStateEntry>).Add(manager.GetObjectStateEntry(entityKey)); } else if (objectStateEntries == null) { objectStateEntries = manager.GetObjectStateEntries(~EntityState.Detached); } dump.AppendFormat("ObjectStateManager entries : # {0}\n", objectStateEntries.Count()); foreach (var entry in objectStateEntries) { dump.Append(ObjectStateEntryToString(entry)); if (entry.State == EntityState.Added) { for (int i = 0; i < entry.CurrentValues.FieldCount; i++) { dump.AppendFormat("\n\t- {0} = {1}", entry.CurrentValues.GetName(i), ObjectToString(entry.CurrentValues[i])); } } else if (entry.State == EntityState.Modified) { foreach (string prop in entry.GetModifiedProperties()) { dump.AppendFormat("\n\t- {0} : {1} -> {2}", prop, ObjectToString(entry.OriginalValues[prop]), ObjectToString(entry.CurrentValues[prop])); } } } if (asHtml) { dump.Replace("\n", "<br />"); dump.Replace("\t", " "); } else { dump.Replace("<b>", ""); dump.Replace("</b>", ""); } return dump.ToString(); }
/// <summary> /// /// </summary> /// <param name="metadata"></param> /// <param name="memberInfo"></param> /// <param name="entityKey"></param> public EntityRecordInfo(EntityType metadata, IEnumerable<EdmMember> memberInfo, EntityKey entityKey, EntitySet entitySet) : base(TypeUsage.Create(metadata), memberInfo) { EntityUtil.CheckArgumentNull<EntityKey>(entityKey, "entityKey"); EntityUtil.CheckArgumentNull(entitySet, "entitySet"); _entityKey = entityKey; _entitySet = entitySet; ValidateEntityType(entitySet); }
public RelationshipChange(EntityKey sourceKey, EntityKey targetKey, object source, object target, EntitySetBase entitySet, EntityState state) { _sourceKey = sourceKey; _targetKey = targetKey; _source = source; _target = target; _entitySet = entitySet; _state = state; }
public ManagementObjectsViewModel() { using (var context = new MCDatabaseModelContainer()) { var key = new EntityKey(); context.ObjectStateManager.GetObjectStateEntry(key); Buildings = context.Buildings.ToList(); } }
public EntityRecordInfo(EntityType metadata, IEnumerable<EdmMember> memberInfo, EntityKey entityKey, EntitySet entitySet) : base(TypeUsage.Create(metadata), memberInfo) { Contract.Requires(entityKey != null); Contract.Requires(entitySet != null); _entityKey = entityKey; ValidateEntityType(entitySet); }
public EntityRecordInfo(EntityType metadata, IEnumerable<EdmMember> memberInfo, EntityKey entityKey, EntitySet entitySet) : base(TypeUsage.Create(metadata), memberInfo) { Check.NotNull(entityKey, "entityKey"); Check.NotNull(entitySet, "entitySet"); _entityKey = entityKey; ValidateEntityType(entitySet); }
public override void DetachFromModel() { if (Detached) return; key.PropertyChanged -= key_PropertyChanged; key.PropertiesChanged -= key_PropertiesChanged; key.Parent.PropertyChanged -= Entity_PropertyChanged; key = null; Detached = true; }
public async Task EntityKeyNoMetadata() { try { var ek = new EntityKey(typeof(FooEntity), MetadataStore.Detached, 7); Assert.Fail("should not get here"); } catch (Exception e) { Assert.IsTrue(e.Message.Contains("FooEntity") && e.Message.Contains("FetchMetadata")); } }
public static HotSpot GetHotSpot(String BssidToGet) { HotSpot obj = new HotSpot(); using (var context = new HotSpotsDBEntities()) { EntityKey key = new EntityKey("HotSpotsDBEntities.HotSpot", "bssid", BssidToGet); obj = (HotSpot)context.GetObjectByKey(key); } return obj; }
/// <summary> /// Returns true if the supplied key represents a Conceptual Null /// </summary> /// <param name="key"> The key to be checked </param> public static bool IsConceptualNullKey(EntityKey key) { if (key == null) { return false; } return string.Equals(key.EntityContainerName, s_NullPart) && string.Equals(key.EntitySetName, s_NullPart); }
public void RemoveChildren(EntityKey parentEntityKey, NavigationProperty navProp) { var navChildrenList = GetNavChildrenList(parentEntityKey, false); if (navChildrenList == null) return; var ix = navChildrenList.IndexOf(nc => nc.NavigationProperty == navProp); if (ix != -1) return; navChildrenList.RemoveAt(ix); if (navChildrenList.Count == 0) { _map.Remove(parentEntityKey); } }
/// <summary> /// Checks if the Real Key represents different FK values /// than those present when the Conceptual Null was created /// </summary> /// <param name="conceptualNullKey"> The key representing the Conceptual Null </param> /// <param name="realKey"> The key to be checked </param> /// <returns> True if the values are different, false otherwise </returns> public static bool IsConceptualNullKeyChanged(EntityKey conceptualNullKey, EntityKey realKey) { Debug.Assert(IsConceptualNullKey(conceptualNullKey), "The key supplied is not a null key"); if (realKey == null) { return true; } return !EntityKey.InternalEquals(conceptualNullKey, realKey, compareEntitySets: false); }
public virtual void AddEntityToIndex(EntityKey entityKey, Document doc) { string key = _parent.GetEntityKeyInCache(entityKey); // adding key to index (it's essential to do this _before_ checking the key length - the index should fail to be read next time) _index.Index.Add(entityKey); // Putting the entity to cache, but only if it doesn't exist there. // That's because when loading from DynamoDb whe should never overwrite local updates. _parent._cacheClient.SetValue(key, new CacheDocumentWrapper(doc)); }
internal static Mock<IEntityWrapper> CreateMockEntityWrapper() { var mockEntityWrapper = new Mock<IEntityWrapper>(MockBehavior.Strict); var entityWithRelationshipsMock = new Mock<IEntityWithRelationships>(MockBehavior.Strict); mockEntityWrapper.Setup(m => m.Entity).Returns(entityWithRelationshipsMock.Object); var entityKey = new EntityKey(qualifiedEntitySetName: "entityContainerName.entitySetName"); mockEntityWrapper.Setup(m => m.EntityKey).Returns(entityKey); return mockEntityWrapper; }
public void Delete(CultureInfo culture, EntityKey key) { using (var db = new MultilingualDbContext(InstanceName)) { var entry = db.Translations.Find(GetUnderlyingEntityKey(culture.Name, key)); if (entry != null) { db.Translations.Remove(entry); db.SaveChanges(); } } }
public async Task FetchByKey() { var em1 = await TestFns.NewEm(_serviceName); var q = new EntityQuery<Fruit>().From("Fruits"); var r0 = await em1.ExecuteQuery(q); Assert.IsTrue(r0.Count() > 0); var fruit1 = r0.First(); var id = fruit1.Id; var ek = new EntityKey(typeof(Fruit), em1.MetadataStore, id); var r1 = await em1.ExecuteQuery(ek.ToQuery()); var fruits = r1.Cast<Fruit>(); Assert.IsTrue(fruits.First() == fruit1); }
public List<NavChildren> GetNavChildrenList(EntityKey entityKey, bool createIfNotFound) { List<NavChildren> navChildrenList = null; if (_map.TryGetValue(entityKey, out navChildrenList)) { return navChildrenList; } else { if (createIfNotFound) { navChildrenList = new List<NavChildren>(); _map.Add(entityKey, navChildrenList); } } return navChildrenList; }
private void UpdateResources() { Resources.Clear(); if(!String.IsNullOrEmpty(resourceIds)) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(resourceIds); foreach(XmlNode xmlNode in xmlDocument.DocumentElement.ChildNodes) { EntityKey entityKey = new EntityKey(objectContext.DefaultContainerName + ".Resources", "Key", Int32.Parse(xmlNode.Attributes["Value"].Value)); Object obj = null; if(objectContext.TryGetObjectByKey(entityKey, out obj)) { Resources.Add((Resource)obj); } } } }
public static void DeleteHotSpot(String BssidToDelete) { HotSpot obj = new HotSpot(); using (var context = new HotSpotsDBEntities()) { EntityKey key = new EntityKey("HotSpotsDBEntities.HotSpot", "bssid", BssidToDelete); obj = (HotSpot)context.GetObjectByKey(key); if (obj != null) { context.DeleteObject(obj); } context.SaveChanges(); } }
public static bool Equals(EntityKey a, EntityKey b) { return(EntityKeyComparer.Instance.Compare(a, b) == 0); }
public virtual async Task OnMergeAsync(MergeEvent @event, IDictionary copiedAlready, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); EventCache copyCache = (EventCache)copiedAlready; IEventSource source = @event.Session; object original = @event.Original; if (original != null) { object entity; if (original.IsProxy()) { ILazyInitializer li = ((INHibernateProxy)original).HibernateLazyInitializer; if (li.IsUninitialized) { log.Debug("ignoring uninitialized proxy"); @event.Result = await(source.LoadAsync(li.EntityName, li.Identifier, cancellationToken)).ConfigureAwait(false); return; //EARLY EXIT! } else { entity = await(li.GetImplementationAsync(cancellationToken)).ConfigureAwait(false); } } else { entity = original; } if (copyCache.Contains(entity) && copyCache.IsOperatedOn(entity)) { log.Debug("already in merge process"); @event.Result = entity; } else { if (copyCache.Contains(entity)) { log.Info("already in copyCache; setting in merge process"); copyCache.SetOperatedOn(entity, true); } @event.Entity = entity; EntityState entityState = EntityState.Undefined; if (ReferenceEquals(null, @event.EntityName)) { @event.EntityName = source.BestGuessEntityName(entity); } // Check the persistence context for an entry relating to this // entity to be merged... EntityEntry entry = source.PersistenceContext.GetEntry(entity); if (entry == null) { IEntityPersister persister = source.GetEntityPersister(@event.EntityName, entity); object id = persister.GetIdentifier(entity); if (id != null) { EntityKey key = source.GenerateEntityKey(id, persister); object managedEntity = source.PersistenceContext.GetEntity(key); entry = source.PersistenceContext.GetEntry(managedEntity); if (entry != null) { // we have specialized case of a detached entity from the // perspective of the merge operation. Specifically, we // have an incoming entity instance which has a corresponding // entry in the current persistence context, but registered // under a different entity instance entityState = EntityState.Detached; } } } if (entityState == EntityState.Undefined) { entityState = await(GetEntityStateAsync(entity, @event.EntityName, entry, source, cancellationToken)).ConfigureAwait(false); } switch (entityState) { case EntityState.Persistent: await(EntityIsPersistentAsync(@event, copyCache, cancellationToken)).ConfigureAwait(false); break; case EntityState.Transient: await(EntityIsTransientAsync(@event, copyCache, cancellationToken)).ConfigureAwait(false); break; case EntityState.Detached: await(EntityIsDetachedAsync(@event, copyCache, cancellationToken)).ConfigureAwait(false); break; default: throw new ObjectDeletedException("deleted instance passed to merge", null, GetLoggableName(@event.EntityName, entity)); } } } }
public EntityKey ForgetEdgeFromNode(EntityKey fromNode) { return(new EntityKey(_setName, _inboundEdges.Where(e => e != fromNode._setName))); }
/// <summary> /// Applies to join a group /// </summary> /// <param name="AutoAcceptOutstandingInvite">Optional, default true. Automatically accept an outstanding invitation if one exists instead of creating an application (Optional)</param> /// <param name="Entity">The entity to perform this action on. (Optional)</param> /// <param name="Group">The identifier of the group (Required)</param> public static Task <ApplyToGroupResponse> ApplyToGroup(EntityKey Group, bool?AutoAcceptOutstandingInvite = default, EntityKey Entity = default, PlayFabAuthenticationContext customAuthContext = null, object customData = null, Dictionary <string, string> extraHeaders = null) { ApplyToGroupRequest request = new ApplyToGroupRequest() { Group = Group, AutoAcceptOutstandingInvite = AutoAcceptOutstandingInvite, Entity = Entity, }; var context = GetContext(customAuthContext); return(PlayFabHttp.MakeApiCallAsync <ApplyToGroupResponse>("/Group/ApplyToGroup", request, AuthType.EntityToken, customData, extraHeaders, context)); }
/// <inheritdoc /> public async Task <int> ProcessResultsSetAsync(DbDataReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfNotInitialized(); var dialect = Session.Factory.Dialect; var hydratedObjects = new List <object> [_queryInfos.Count]; var isDebugLog = Log.IsDebugEnabled(); using (Session.SwitchCacheMode(_cacheMode)) { var rowCount = 0; for (var i = 0; i < _queryInfos.Count; i++) { var queryInfo = _queryInfos[i]; var loader = queryInfo.Loader; var queryParameters = queryInfo.Parameters; //Skip processing for items already loaded from cache if (queryInfo.IsResultFromCache) { continue; } var entitySpan = loader.EntityPersisters.Length; hydratedObjects[i] = entitySpan == 0 ? null : new List <object>(entitySpan); var keys = new EntityKey[entitySpan]; var selection = queryParameters.RowSelection; var createSubselects = loader.IsSubselectLoadingEnabled; _subselectResultKeys[i] = createSubselects ? new List <EntityKey[]>() : null; var maxRows = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; var advanceSelection = !dialect.SupportsLimitOffset || !loader.UseLimit(selection, dialect); if (advanceSelection) { await(Loader.Loader.AdvanceAsync(reader, selection, cancellationToken)).ConfigureAwait(false); } var forcedResultTransformer = queryInfo.CacheKey?.ResultTransformer; if (queryParameters.HasAutoDiscoverScalarTypes) { loader.AutoDiscoverTypes(reader, queryParameters, forcedResultTransformer); } var lockModeArray = loader.GetLockModes(queryParameters.LockModes); var optionalObjectKey = Loader.Loader.GetOptionalObjectKey(queryParameters, Session); var tmpResults = new List <object>(); var queryCacheBuilder = queryInfo.IsCacheable ? new QueryCacheResultBuilder(loader) : null; var cacheBatcher = queryInfo.CacheBatcher; var ownCacheBatcher = cacheBatcher == null; if (ownCacheBatcher) { cacheBatcher = new CacheBatcher(Session); } if (isDebugLog) { Log.Debug("processing result set"); } int count; for (count = 0; count < maxRows && await(reader.ReadAsync(cancellationToken)).ConfigureAwait(false); count++) { if (isDebugLog) { Log.Debug("result set row: {0}", count); } rowCount++; var o = await(loader.GetRowFromResultSetAsync( reader, Session, queryParameters, lockModeArray, optionalObjectKey, hydratedObjects[i], keys, true, forcedResultTransformer, queryCacheBuilder, (persister, data) => cacheBatcher.AddToBatch(persister, data) , cancellationToken)).ConfigureAwait(false); if (loader.IsSubselectLoadingEnabled) { _subselectResultKeys[i].Add(keys); keys = new EntityKey[entitySpan]; //can't reuse in this case } tmpResults.Add(o); } if (isDebugLog) { Log.Debug("done processing result set ({0} rows)", count); } queryInfo.Result = tmpResults; if (queryInfo.CanPutToCache) { queryInfo.ResultToCache = queryCacheBuilder.Result; } if (ownCacheBatcher) { await(cacheBatcher.ExecuteBatchAsync(cancellationToken)).ConfigureAwait(false); } await(reader.NextResultAsync(cancellationToken)).ConfigureAwait(false); } StopLoadingCollections(reader); _reader = reader; _hydratedObjects = hydratedObjects; return(rowCount); } }
public Task <object> GetEntityUsingInterceptorAsync(EntityKey key, CancellationToken cancellationToken) { return(_session.GetEntityUsingInterceptorAsync(key, cancellationToken)); }
public abstract WeaponEntity ReplaceWeapon(EntityKey Owner, WeaponScanStruct orient, ref WeaponPartsRefreshStruct refreshParams);
private void GetResultsFromDatabase(IList results) { bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled; var stopWatch = new Stopwatch(); if (statsEnabled) { stopWatch.Start(); } int rowCount = 0; try { using (var reader = resultSetsCommand.GetReader(parameters.ToArray(), null)) { ArrayList[] hydratedObjects = new ArrayList[loaders.Count]; List <EntityKey[]>[] subselectResultKeys = new List <EntityKey[]> [loaders.Count]; bool[] createSubselects = new bool[loaders.Count]; for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; int entitySpan = loader.EntityPersisters.Length; hydratedObjects[i] = entitySpan == 0 ? null : new ArrayList(entitySpan); EntityKey[] keys = new EntityKey[entitySpan]; QueryParameters queryParameters = parameters[i]; IList tmpResults = new ArrayList(); RowSelection selection = parameters[i].RowSelection; createSubselects[i] = loader.IsSubselectLoadingEnabled; subselectResultKeys[i] = createSubselects[i] ? new List <EntityKey[]>() : null; int maxRows = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; if (!dialect.SupportsLimitOffset || !Loader.Loader.UseLimit(selection, dialect)) { Loader.Loader.Advance(reader, selection); } int count; for (count = 0; count < maxRows && reader.Read(); count++) { rowCount++; object o = loader.GetRowFromResultSet(reader, session, queryParameters, loader.GetLockModes(queryParameters.LockModes), null, hydratedObjects[i], keys, true); if (createSubselects[i]) { subselectResultKeys[i].Add(keys); keys = new EntityKey[entitySpan]; //can't reuse in this case } tmpResults.Add(o); } results.Add(tmpResults); reader.NextResult(); } for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; loader.InitializeEntitiesAndCollections(hydratedObjects[i], reader, session, false); if (createSubselects[i]) { loader.CreateSubselects(subselectResultKeys[i], parameters[i], session); } } } } catch (Exception sqle) { var message = string.Format("Failed to execute multi criteria: [{0}]", resultSetsCommand.Sql); log.Error(message, sqle); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi criteria", resultSetsCommand.Sql); } if (statsEnabled) { stopWatch.Stop(); session.Factory.StatisticsImplementor.QueryExecuted(string.Format("{0} queries (MultiCriteria)", loaders.Count), rowCount, stopWatch.Elapsed); } }
public virtual async Task OnRefreshAsync(RefreshEvent @event, IDictionary refreshedAlready, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); IEventSource source = @event.Session; bool isTransient = !source.Contains(@event.Entity); if (source.PersistenceContext.ReassociateIfUninitializedProxy(@event.Entity)) { if (isTransient) { source.SetReadOnly(@event.Entity, source.DefaultReadOnly); } return; } object obj = await(source.PersistenceContext.UnproxyAndReassociateAsync(@event.Entity, cancellationToken)).ConfigureAwait(false); if (refreshedAlready.Contains(obj)) { log.Debug("already refreshed"); return; } EntityEntry e = source.PersistenceContext.GetEntry(obj); IEntityPersister persister; object id; if (e == null) { persister = source.GetEntityPersister(source.BestGuessEntityName(obj), obj); //refresh() does not pass an entityName id = persister.GetIdentifier(obj); if (log.IsDebugEnabled()) { log.Debug("refreshing transient {0}", MessageHelper.InfoString(persister, id, source.Factory)); } EntityKey key = source.GenerateEntityKey(id, persister); if (source.PersistenceContext.GetEntry(key) != null) { throw new PersistentObjectException("attempted to refresh transient instance when persistent instance was already associated with the Session: " + MessageHelper.InfoString(persister, id, source.Factory)); } } else { if (log.IsDebugEnabled()) { log.Debug("refreshing {0}", MessageHelper.InfoString(e.Persister, e.Id, source.Factory)); } if (!e.ExistsInDatabase) { throw new HibernateException("this instance does not yet exist as a row in the database"); } persister = e.Persister; id = e.Id; } // cascade the refresh prior to refreshing this entity refreshedAlready[obj] = obj; await(new Cascade(CascadingAction.Refresh, CascadePoint.BeforeRefresh, source).CascadeOnAsync(persister, obj, refreshedAlready, cancellationToken)).ConfigureAwait(false); if (e != null) { EntityKey key = source.GenerateEntityKey(id, persister); source.PersistenceContext.RemoveEntity(key); if (persister.HasCollections) { await(new EvictVisitor(source).ProcessAsync(obj, persister, cancellationToken)).ConfigureAwait(false); } } if (persister.HasCache) { CacheKey ck = source.GenerateCacheKey(id, persister.IdentifierType, persister.RootEntityName); await(persister.Cache.RemoveAsync(ck, cancellationToken)).ConfigureAwait(false); } await(EvictCachedCollectionsAsync(persister, id, source.Factory, cancellationToken)).ConfigureAwait(false); // NH Different behavior : NH-1601 // At this point the entity need the real refresh, all elementes of collections are Refreshed, // the collection state was evicted, but the PersistentCollection (in the entity state) // is associated with a possible previous session. await(new WrapVisitor(source).ProcessAsync(obj, persister, cancellationToken)).ConfigureAwait(false); string previousFetchProfile = source.FetchProfile; source.FetchProfile = "refresh"; object result = await(persister.LoadAsync(id, obj, @event.LockMode, source, cancellationToken)).ConfigureAwait(false); if (result != null) { if (!persister.IsMutable) { source.SetReadOnly(result, true); } else { source.SetReadOnly(result, e == null ? source.DefaultReadOnly : !e.IsModifiableEntity()); } } source.FetchProfile = previousFetchProfile; // NH Different behavior : we are ignoring transient entities without throw any kind of exception // because a transient entity is "self refreshed" if (!(await(ForeignKeys.IsTransientFastAsync(persister.EntityName, obj, @event.Session, cancellationToken)).ConfigureAwait(false)).GetValueOrDefault(result == null)) { UnresolvableObjectException.ThrowIfNull(result, id, persister.EntityName); } }
// <summary> // Call to ensure a target entities key is added into the state manager // properly // </summary> public IEntityWrapper HandleRelationshipSpan( IEntityWrapper wrappedEntity, EntityKey targetKey, AssociationEndMember targetMember) { if (null == wrappedEntity.Entity) { return(wrappedEntity); } DebugCheck.NotNull(targetMember); Debug.Assert( targetMember.RelationshipMultiplicity == RelationshipMultiplicity.One || targetMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne); var sourceKey = wrappedEntity.EntityKey; var sourceMember = MetadataHelper.GetOtherAssociationEnd(targetMember); CheckClearedEntryOnSpan(targetKey, wrappedEntity, sourceKey, targetMember); if (null != (object)targetKey) { EntitySet targetEntitySet; var associationSet = Context.MetadataWorkspace.MetadataOptimization.FindCSpaceAssociationSet( (AssociationType)targetMember.DeclaringType, targetMember.Name, targetKey.EntitySetName, targetKey.EntityContainerName, out targetEntitySet); Debug.Assert(associationSet != null, "associationSet should not be null"); var manager = Context.ObjectStateManager; EntityState newEntryState; // If there is an existing relationship entry, update it based on its current state and the MergeOption, otherwise add a new one if ( !ObjectStateManager.TryUpdateExistingRelationships( Context, MergeOption, associationSet, sourceMember, sourceKey, wrappedEntity, targetMember, targetKey, /*setIsLoaded*/ true, out newEntryState)) { // Try to find a state entry for the target key var targetEntry = manager.GetOrAddKeyEntry(targetKey, targetEntitySet); // For 1-1 relationships we have to take care of the relationships of targetEntity var needNewRelationship = true; switch (sourceMember.RelationshipMultiplicity) { case RelationshipMultiplicity.ZeroOrOne: case RelationshipMultiplicity.One: // devnote: targetEntry can be a key entry (targetEntry.Entity == null), // but it that case this parameter won't be used in TryUpdateExistingRelationships needNewRelationship = !ObjectStateManager.TryUpdateExistingRelationships( Context, MergeOption, associationSet, targetMember, targetKey, targetEntry.WrappedEntity, sourceMember, sourceKey, setIsLoaded: true, newEntryState: out newEntryState); // It is possible that as part of removing existing relationships, the key entry was deleted // If that is the case, recreate the key entry if (targetEntry.State == EntityState.Detached) { targetEntry = manager.AddKeyEntry(targetKey, targetEntitySet); } break; case RelationshipMultiplicity.Many: // we always need a new relationship with Many-To-Many, if there was no exact match between these two entities, so do nothing break; default: Debug.Assert(false, "Unexpected sourceMember.RelationshipMultiplicity"); break; } if (needNewRelationship) { // If the target entry is a key entry, then we need to add a relation // between the source and target entries // If we are in a state where we just need to add a new Deleted relation, we // only need to do that and not touch the related ends // If the target entry is a full entity entry, then we need to add // the target entity to the source collection or reference if (targetEntry.IsKeyEntry || newEntryState == EntityState.Deleted) { // Add a relationship between the source entity and the target key entry var wrapper = new RelationshipWrapper( associationSet, sourceMember.Name, sourceKey, targetMember.Name, targetKey); manager.AddNewRelation(wrapper, newEntryState); } else { Debug.Assert(!targetEntry.IsRelationship, "how IsRelationship?"); if (targetEntry.State != EntityState.Deleted) { // The entry contains an entity, do collection or reference fixup // This will also try to create a new relationship entry or will revert the delete on an existing deleted relationship ObjectStateManager.AddEntityToCollectionOrReference( MergeOption, wrappedEntity, sourceMember, targetEntry.WrappedEntity, targetMember, setIsLoaded: true, relationshipAlreadyExists: false, inKeyEntryPromotion: false); } else { // if the target entry is deleted, then the materializer needs to create a deleted relationship // between the entity and the target entry so that if the entity is deleted, the update // pipeline can find the relationship (even though it is deleted) var wrapper = new RelationshipWrapper( associationSet, sourceMember.Name, sourceKey, targetMember.Name, targetKey); manager.AddNewRelation(wrapper, EntityState.Deleted); } } } } } else { RelatedEnd relatedEnd; if (TryGetRelatedEnd( wrappedEntity, (AssociationType)targetMember.DeclaringType, sourceMember.Name, targetMember.Name, out relatedEnd)) { SetIsLoadedForSpan(relatedEnd, false); } } // else there is nothing else for us to do, the relationship has been handled already return(wrappedEntity); }
// <summary> // REQUIRES:: entity exists; MergeOption is AppendOnly // Handles state management for an entity with the given key. When the entity already exists // in the state manager, it is returned directly. Otherwise, the entityDelegate is invoked and // the resulting entity is returned. // </summary> public IEntityWrapper HandleEntityAppendOnly <TEntity>( Func <Shaper, IEntityWrapper> constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) { Debug.Assert(MergeOption == MergeOption.AppendOnly, "only use HandleEntityAppendOnly when MergeOption is AppendOnly"); DebugCheck.NotNull(constructEntityDelegate); IEntityWrapper result; if (null == (object)entityKey) { // no entity set, so no tracking is required for this entity, just // call the delegate to "materialize" it. result = constructEntityDelegate(this); RegisterMaterializedEntityForEvent(result); } else { Debug.Assert(null != entitySet, "if there is an entity key, there must also be an entity set"); // check for an existing entity with the same key var existingEntry = Context.ObjectStateManager.FindEntityEntry(entityKey); if (null != existingEntry && !existingEntry.IsKeyEntry) { Debug.Assert(existingEntry.EntityKey.Equals(entityKey), "Found ObjectStateEntry with wrong EntityKey"); if (typeof(TEntity) != existingEntry.WrappedEntity.IdentityType) { var key = existingEntry.EntityKey; throw new NotSupportedException( Strings.Materializer_RecyclingEntity( TypeHelpers.GetFullName(key.EntityContainerName, key.EntitySetName), typeof(TEntity).FullName, existingEntry.WrappedEntity.IdentityType.FullName)); } if (EntityState.Added == existingEntry.State) { throw new InvalidOperationException( Strings.Materializer_AddedEntityAlreadyExists(typeof(TEntity).FullName)); } result = existingEntry.WrappedEntity; } else { // We don't already have the entity, so construct it result = constructEntityDelegate(this); RegisterMaterializedEntityForEvent(result); if (null == existingEntry) { Context.ObjectStateManager.AddEntry(result, entityKey, entitySet, "HandleEntity", false); } else { Context.ObjectStateManager.PromoteKeyEntry( existingEntry, result, false, /*setIsLoaded*/ true, /*keyEntryInitialized*/ false); } } } return(result); }
protected virtual async Task PerformUpdateAsync(SaveOrUpdateEvent @event, object entity, IEntityPersister persister, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!persister.IsMutable) { log.Debug("immutable instance passed to PerformUpdate(), locking"); } if (log.IsDebugEnabled()) { log.Debug("updating {0}", MessageHelper.InfoString(persister, @event.RequestedId, @event.Session.Factory)); } IEventSource source = @event.Session; EntityKey key = source.GenerateEntityKey(@event.RequestedId, persister); source.PersistenceContext.CheckUniqueness(key, entity); if (InvokeUpdateLifecycle(entity, persister, source)) { await(ReassociateAsync(@event, @event.Entity, @event.RequestedId, persister, cancellationToken)).ConfigureAwait(false); return; } // this is a transient object with existing persistent state not loaded by the session await(new OnUpdateVisitor(source, @event.RequestedId, entity).ProcessAsync(entity, persister, cancellationToken)).ConfigureAwait(false); //TODO: put this stuff back in to read snapshot from // the second-level cache (needs some extra work) /*Object[] cachedState = null; * * if ( persister.hasCache() ) { * CacheEntry entry = (CacheEntry) persister.getCache() * .get( event.getRequestedId(), source.getTimestamp() ); * cachedState = entry==null ? * null : * entry.getState(); //TODO: half-assemble this stuff * }*/ source.PersistenceContext.AddEntity( entity, persister.IsMutable ? Status.Loaded : Status.ReadOnly, null, key, persister.GetVersion(entity), LockMode.None, true, persister, false); //persister.AfterReassociate(entity, source); TODO H3.2 not ported if (log.IsDebugEnabled()) { log.Debug("updating {0}", MessageHelper.InfoString(persister, @event.RequestedId, source.Factory)); } await(CascadeOnUpdateAsync(@event, persister, entity, cancellationToken)).ConfigureAwait(false); }
public static EntityKey Deserialize(EntityKey typeTag, BinaryReader reader) { return(_entityKeySerializer.Read(reader)); }
protected List <object> DoList() { bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled; var stopWatch = new Stopwatch(); if (statsEnabled) { stopWatch.Start(); } int rowCount = 0; var results = new List <object>(); var hydratedObjects = new List <object> [Translators.Count]; List <EntityKey[]>[] subselectResultKeys = new List <EntityKey[]> [Translators.Count]; bool[] createSubselects = new bool[Translators.Count]; try { using (var reader = resultSetsCommand.GetReader(_timeout)) { if (log.IsDebugEnabled()) { log.Debug("Executing {0} queries", translators.Count); } for (int i = 0; i < translators.Count; i++) { ITranslator translator = Translators[i]; QueryParameters parameter = Parameters[i]; int entitySpan = translator.Loader.EntityPersisters.Length; hydratedObjects[i] = entitySpan > 0 ? new List <object>() : null; RowSelection selection = parameter.RowSelection; int maxRows = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; if (!dialect.SupportsLimitOffset || !translator.Loader.UseLimit(selection, dialect)) { Loader.Loader.Advance(reader, selection); } if (parameter.HasAutoDiscoverScalarTypes) { translator.Loader.AutoDiscoverTypes(reader, parameter, null); } LockMode[] lockModeArray = translator.Loader.GetLockModes(parameter.LockModes); EntityKey optionalObjectKey = Loader.Loader.GetOptionalObjectKey(parameter, session); createSubselects[i] = translator.Loader.IsSubselectLoadingEnabled; subselectResultKeys[i] = createSubselects[i] ? new List <EntityKey[]>() : null; translator.Loader.HandleEmptyCollections(parameter.CollectionKeys, reader, session); EntityKey[] keys = new EntityKey[entitySpan]; // we can reuse it each time if (log.IsDebugEnabled()) { log.Debug("processing result set"); } IList tempResults = new List <object>(); int count; for (count = 0; count < maxRows && reader.Read(); count++) { if (log.IsDebugEnabled()) { log.Debug("result set row: {0}", count); } rowCount++; object result = translator.Loader.GetRowFromResultSet( reader, session, parameter, lockModeArray, optionalObjectKey, hydratedObjects[i], keys, true); tempResults.Add(result); if (createSubselects[i]) { subselectResultKeys[i].Add(keys); keys = new EntityKey[entitySpan]; //can't reuse in this case } } if (log.IsDebugEnabled()) { log.Debug("done processing result set ({0} rows)", count); } results.Add(tempResults); if (log.IsDebugEnabled()) { log.Debug("Query {0} returned {1} results", i, tempResults.Count); } reader.NextResult(); } for (int i = 0; i < translators.Count; i++) { ITranslator translator = translators[i]; QueryParameters parameter = parameters[i]; translator.Loader.InitializeEntitiesAndCollections(hydratedObjects[i], reader, session, false); if (createSubselects[i]) { translator.Loader.CreateSubselects(subselectResultKeys[i], parameter, session); } } } } catch (Exception sqle) { log.Error(sqle, "Failed to execute multi query: [{0}]", resultSetsCommand.Sql); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi query", resultSetsCommand.Sql); } if (statsEnabled) { stopWatch.Stop(); session.Factory.StatisticsImplementor.QueryExecuted(string.Format("{0} queries (MultiQuery)", translators.Count), rowCount, stopWatch.Elapsed); } return(results); }
public object GetEntityUsingInterceptor(EntityKey key) { return(_session.GetEntityUsingInterceptor(key)); }
public static void Serialize(EntityKey data, Core.Utils.MyBinaryWriter writer, EntityKey last = default(EntityKey), bool weiteAll = false) { _entityKeySerializer.Write(data, writer); }
/// <summary> /// Performs all the actual work needed to save an entity (well to get the save moved to /// the execution queue). /// </summary> /// <param name="entity">The entity to be saved </param> /// <param name="key">The id to be used for saving the entity (or null, in the case of identity columns) </param> /// <param name="persister">The entity's persister instance. </param> /// <param name="useIdentityColumn">Should an identity column be used for id generation? </param> /// <param name="anything">Generally cascade-specific information. </param> /// <param name="source">The session which is the source of the current event. </param> /// <param name="requiresImmediateIdAccess"> /// Is access to the identifier required immediately /// after the completion of the save? persist(), for example, does not require this... /// </param> /// <returns> /// The id used to save the entity; may be null depending on the /// type of id generator used and the requiresImmediateIdAccess value /// </returns> protected virtual object PerformSaveOrReplicate(object entity, EntityKey key, IEntityPersister persister, bool useIdentityColumn, object anything, IEventSource source, bool requiresImmediateIdAccess) { Validate(entity, persister, source); object id = key == null ? null : key.Identifier; // NH Different behavior (shouldDelayIdentityInserts=false anyway) //bool inTxn = source.ConnectionManager.IsInActiveTransaction; //bool shouldDelayIdentityInserts = !inTxn && !requiresImmediateIdAccess; bool shouldDelayIdentityInserts = false; // Put a placeholder in entries, so we don't recurse back and try to save() the // same object again. QUESTION: should this be done before onSave() is called? // likewise, should it be done before onUpdate()? source.PersistenceContext.AddEntry(entity, Status.Saving, null, null, id, null, LockMode.Write, useIdentityColumn, persister, false, false); CascadeBeforeSave(source, persister, entity, anything); // NH-962: This was originally done before many-to-one cascades. if (useIdentityColumn && !shouldDelayIdentityInserts) { log.Debug("executing insertions"); source.ActionQueue.ExecuteInserts(); } object[] values = persister.GetPropertyValuesToInsert(entity, GetMergeMap(anything), source); IType[] types = persister.PropertyTypes; bool substitute = SubstituteValuesIfNecessary(entity, id, values, persister, source); if (persister.HasCollections) { substitute = substitute || VisitCollectionsBeforeSave(entity, id, values, types, source); } if (substitute) { persister.SetPropertyValues(entity, values, source.EntityMode); } TypeHelper.DeepCopy(values, types, persister.PropertyUpdateability, values, source); new ForeignKeys.Nullifier(entity, false, useIdentityColumn, source).NullifyTransientReferences(values, types); new Nullability(source).CheckNullability(values, persister, false); if (useIdentityColumn) { EntityIdentityInsertAction insert = new EntityIdentityInsertAction(values, entity, persister, source, shouldDelayIdentityInserts); if (!shouldDelayIdentityInserts) { log.Debug("executing identity-insert immediately"); source.ActionQueue.Execute(insert); id = insert.GeneratedId; //now done in EntityIdentityInsertAction //persister.setIdentifier( entity, id, source.getEntityMode() ); key = source.GenerateEntityKey(id, persister); source.PersistenceContext.CheckUniqueness(key, entity); //source.getBatcher().executeBatch(); //found another way to ensure that all batched joined inserts have been executed } else { log.Debug("delaying identity-insert due to no transaction in progress"); source.ActionQueue.AddAction(insert); key = insert.DelayedEntityKey; } } object version = Versioning.GetVersion(values, persister); source.PersistenceContext.AddEntity( entity, persister.IsMutable ? Status.Loaded : Status.ReadOnly, values, key, version, LockMode.Write, useIdentityColumn, persister, VersionIncrementDisabled, false); //source.getPersistenceContext().removeNonExist( new EntityKey( id, persister, source.getEntityMode() ) ); if (!useIdentityColumn) { source.ActionQueue.AddAction(new EntityInsertAction(id, values, entity, version, persister, source)); } CascadeAfterSave(source, persister, entity, anything); MarkInterceptorDirty(entity, persister, source); return(id); }
public KeyValue([NotNull] IForeignKey foreignKey, EntityKey keyValue, ValueType valueType) { ForeignKey = foreignKey; Key = keyValue; ValueType = valueType; }
private async Task GetResultsFromDatabaseAsync(IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled; var stopWatch = new Stopwatch(); if (statsEnabled) { stopWatch.Start(); } int rowCount = 0; try { using (var reader = await(resultSetsCommand.GetReaderAsync(_timeout, cancellationToken)).ConfigureAwait(false)) { var hydratedObjects = new List <object> [loaders.Count]; List <EntityKey[]>[] subselectResultKeys = new List <EntityKey[]> [loaders.Count]; bool[] createSubselects = new bool[loaders.Count]; for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; int entitySpan = loader.EntityPersisters.Length; hydratedObjects[i] = entitySpan == 0 ? null : new List <object>(entitySpan); EntityKey[] keys = new EntityKey[entitySpan]; QueryParameters queryParameters = parameters[i]; IList tmpResults = new List <object>(); RowSelection selection = parameters[i].RowSelection; createSubselects[i] = loader.IsSubselectLoadingEnabled; subselectResultKeys[i] = createSubselects[i] ? new List <EntityKey[]>() : null; int maxRows = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; if (!dialect.SupportsLimitOffset || !loader.UseLimit(selection, dialect)) { await(Loader.Loader.AdvanceAsync(reader, selection, cancellationToken)).ConfigureAwait(false); } int count; for (count = 0; count < maxRows && await(reader.ReadAsync(cancellationToken)).ConfigureAwait(false); count++) { rowCount++; object o = await(loader.GetRowFromResultSetAsync(reader, session, queryParameters, loader.GetLockModes(queryParameters.LockModes), null, hydratedObjects[i], keys, true, cancellationToken)).ConfigureAwait(false); if (createSubselects[i]) { subselectResultKeys[i].Add(keys); keys = new EntityKey[entitySpan]; //can't reuse in this case } tmpResults.Add(o); } results.Add(tmpResults); await(reader.NextResultAsync(cancellationToken)).ConfigureAwait(false); } for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; await(loader.InitializeEntitiesAndCollectionsAsync(hydratedObjects[i], reader, session, session.DefaultReadOnly, cancellationToken: cancellationToken)).ConfigureAwait(false); if (createSubselects[i]) { loader.CreateSubselects(subselectResultKeys[i], parameters[i], session); } } } } catch (OperationCanceledException) { throw; } catch (Exception sqle) { log.Error(sqle, "Failed to execute multi criteria: [{0}]", resultSetsCommand.Sql); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi criteria", resultSetsCommand.Sql); } if (statsEnabled) { stopWatch.Stop(); session.Factory.StatisticsImplementor.QueryExecuted(string.Format("{0} queries (MultiCriteria)", loaders.Count), rowCount, stopWatch.Elapsed); } }
protected override PlayerEntity GetEntityWithEntityKey(EntityKey entitykey) { return(((PlayerContext)EntitasContext).GetEntityWithEntityKey(entitykey)); }
protected override WeaponEntity GetEntityWithEntityKey(EntityKey entitykey) { return(((WeaponContext)EntitasContext).GetEntityWithEntityKey(entitykey)); }
public object GetObjectByKey(EntityKey key) { return(null); }
/// <summary> /// Lists all outstanding invitations and group applications for an entity /// </summary> /// <param name="Entity">The entity to perform this action on. (Optional)</param> public static Task <ListMembershipOpportunitiesResponse> ListMembershipOpportunities(EntityKey Entity = default, PlayFabAuthenticationContext customAuthContext = null, object customData = null, Dictionary <string, string> extraHeaders = null) { ListMembershipOpportunitiesRequest request = new ListMembershipOpportunitiesRequest() { Entity = Entity, }; var context = GetContext(customAuthContext); return(PlayFabHttp.MakeApiCallAsync <ListMembershipOpportunitiesResponse>("/Group/ListMembershipOpportunities", request, AuthType.EntityToken, customData, extraHeaders, context)); }
/// <summary> /// sync from event of playerEntiy.BagSet.WeaponSlot Component /// </summary> /// <param name="entityKey"></param> internal void Sync(EntityKey entityKey) { entity = WeaponEntityFactory.GetWeaponEntity(WeaponContext, entityKey); }
public override float DecreaseHp(VehiclePartIndex index, float amount, EUIDeadType damageType, EntityKey damageSource) { AssertUtility.Assert(amount >= 0); return(base.DecreaseHp(index, amount, damageType, damageSource)); }
public bool HasIncomingEdgeFromNode(EntityKey node) { return(_inboundEdges.Contains(node._setName)); }
private bool TryExecuteSelectImpl(EntitySession session, EntityCommand command, object[] args, out IList <EntityRecord> records) { records = _empty; var cacheType = command.TargetEntityInfo.CacheType; var entType = command.TargetEntityInfo.EntityType; var fullSet = GetFullyCachedSet(entType); if (fullSet == null) { return(false); } switch (command.Kind) { case EntityCommandKind.SelectAll: case EntityCommandKind.SelectAllPaged: if (cacheType != CacheType.FullSet) { return(false); } if (command.Kind == EntityCommandKind.SelectAllPaged && args.Length == 2) { records = fullSet.Records.Skip((int)args[0]).Take((int)args[1]).ToList(); } else { records = fullSet.Records; } return(true); case EntityCommandKind.SelectByKeyArray: if (cacheType != CacheType.FullSet) { return(false); } //create hashset of values HashSet <object> idSet = new HashSet <object>(); var iEnum = args[0] as IEnumerable; foreach (var v in iEnum) { idSet.Add(v); } records = fullSet.Records.Where(r => idSet.Contains(r.PrimaryKey.Values[0])).ToList(); return(true); case EntityCommandKind.SelectByKey: if (command.SelectKey.KeyType.IsSet(KeyType.PrimaryKey)) { var pk = new EntityKey(command.SelectKey, args); var rec = fullSet.LookupByPrimaryKey(pk); if (rec != null) { records = new EntityRecord[] { rec }; return(true); } else { records = _empty; return(false); // not found, records already set to empty array } }//if PrimaryKey if (command.SelectKey.KeyType.IsSet(KeyType.ForeignKey)) { records = fullSet.Records.Where(rec => rec.KeyMatches(command.SelectKey, args)).ToList(); return(true); } return(false); default: return(false); //never happens }//switch }
/// <summary> /// Return the Underlying Persistent Object in a given <see cref="ISession"/>, or null. /// </summary> /// <param name="s">The Session to get the object from.</param> /// <returns>The Persistent Object this proxy is Proxying, or <see langword="null" />.</returns> public object GetImplementation(ISessionImplementor s) { EntityKey key = s.GenerateEntityKey(Identifier, s.Factory.GetEntityPersister(EntityName)); return(s.PersistenceContext.GetEntity(key)); }
/// <summary> /// 是否赋值 /// </summary> public WeaponBagSlotData() { WeaponKey = EntityKey.EmptyWeapon; }
protected override WeaponEntity GetEntityWithEntityKey(EntityKey entitykey) { return(null); }