private static void ImportSingle(IEntitySet entitySetToCreateIn, string[] headers, string[] data) { // Create the new entity IEntityObject newEntity = entitySetToCreateIn.AddNew(); Microsoft.LightSwitch.Details.IEntityProperty currentProperty; object newValue; // Loop through all propertyNames from the first line of the file for (int i = 0; i < headers.Count() ; i++) { try { // Get the property from the new entity by name currentProperty = newEntity.Details.Properties[headers[i]]; } catch (ArgumentException) { throw new InvalidOperationException(String.Format("A property named {0} does not exist on the entity named {1}.", headers[i], newEntity.Details.Name)); } try { // Convert the value newValue = Convert.ChangeType(data[i], currentProperty.PropertyType, null); currentProperty.Value = newValue; } catch (System.FormatException) { throw new InvalidOperationException(String.Format("The following line has an invalid value for property {0}. Aborting the import.\nData: {1}", headers[i], String.Join(",", data))); } } }
public void ProcessEntitySet(IEntitySet entitySet, bool identitySet = false) { if (entitySet.HasUI()) { ProcessUIEntitySet(entitySet); } using (this.GeneratorConfiguration.PushEntitySet(entitySet)) { foreach (var entity in entitySet.Entities) { if (entity.HasNavigationOrUI() || entity.CanFollowWithout() || identitySet) { using (this.GeneratorConfiguration.BeginChild(entity)) { ProcessEntity(entity, identitySet); } } else { DocumentEntity(entity, identitySet); } } } }
private QueryResult(IEntitySet<TBase> entitySet, IEnumerable<TEntity> resultSet, long? totalCount, Exception exception) { this._entitySet = entitySet; this._resultSet = resultSet; this._totalCount = totalCount; this._exception = exception; }
/// <summary> /// Executes change interceptors and applies changes to the objects set for each entity contained in the change set /// </summary> protected virtual void ApplyChanges <TEntity>(TRepository repository, IEntitySet <TEntity> entitySet, IChangeSet changeSet, IList <TEntity> entityChangeSet, ClientInfo clientInfo) where TEntity : Entity { // apply changes to repository if (entityChangeSet != null && entityChangeSet.Count > 0) { foreach (var entity in entityChangeSet.ToArray()) { // run interceptors ExecuteChangeInterceptors(repository, changeSet, entity, clientInfo); } foreach (var entity in entityChangeSet) { // stop processing if transaction is not active if (Transaction.Current.TransactionInformation.Status != TransactionStatus.Active) { return; } if (IsValid(entity)) { // apply changes entitySet.ApplyChanges(entity); } } } }
private static void PerformImport(System.IO.FileInfo file, IEntitySet entitySetToCreateIn) { using (System.IO.StreamReader reader = file.OpenText()) { string inputLine = reader.ReadLine(); // Get the property names from the first line of input string[] headers = inputLine.Split(',').Select(header => header.Trim()).ToArray(); int count = headers.Count(); string[] data; inputLine = reader.ReadLine(); while (inputLine != null) { data = inputLine.Split(','); // If the right number of data items were found, import the line if (data.Count() == count) { ImportSingle(entitySetToCreateIn, headers, data); } else { throw new InvalidOperationException(String.Format("Line not imported. Invalid number of elements. Data = [{0}].", inputLine)); } inputLine = reader.ReadLine(); } reader.Close(); } entitySetToCreateIn.Details.DataService.SaveChanges(); }
private static void FillDataTableRows(DataTable table, IEntitySet extendList, IList <IProperty> properties, bool hasPrmKey) { FillDataTableRows(table, extendList.GetAttachedList(), properties, hasPrmKey, EntityState.Attached); FillDataTableRows(table, extendList.GetModifiedList(), properties, hasPrmKey, EntityState.Modified); FillDataTableRows(table, extendList.GetDetachedList(), properties, hasPrmKey, EntityState.Detached); extendList.Reset(); }
public bool TryGetLinkedOrInlineEntities( IBindableModelContext context, ODataEntityDto oDataEntity, INavigationProperty navigationProperty, IEntitySet navigationRoot, out IEnumerable <IEntity> entities) { if (navigationProperty.IsContained()) { throw new ArgumentException("Navigation property must be uncontained.", nameof(navigationProperty)); } // parse reference links as well as inline entities (both can be included at the same time) var resultingEntities = new List <IEntity>(); var success = this.TryParseReferencedEntities(context, oDataEntity, navigationProperty, resultingEntities) | this.TryParseAndCreateInlineEntities(context, oDataEntity, navigationProperty, navigationRoot, resultingEntities); if (success) { entities = resultingEntities; return(true); } entities = null; return(false); }
internal void AssignReverseLookupValues2Entity(DataContext m_DataContext, Object _entity, int index) { IEntitySet _entitySet = (IEntitySet)this.m_Storage.GetValue(_entity); Debug.Assert(index > 0, "We try to get reverse lookup for new item."); _entitySet.LoadValues(m_DataContext, (AssociationAttribute)this.m_Description, index); }
protected override bool TryHandleNavigationProperty( IBindableModelContext context, IEntity targetEntity, ODataEntityDto oDataEntity, INavigationProperty navigationProperty, IEntitySet navigationRoot) { if (navigationProperty.IsContained()) { IEnumerable <ODataEntityDto> inlineODataEntities; if (!oDataEntity.TryGetInlineODataEntities(navigationProperty.Name, out inlineODataEntities)) { return(false); } this.CreateInContainedNavigationProperty(context, navigationProperty, navigationRoot, targetEntity, inlineODataEntities); return(true); } IEnumerable <IEntity> entities; if (this.navigationPropertyParser.TryGetLinkedOrInlineEntities(context, oDataEntity, navigationProperty, navigationRoot, out entities)) { this.navigationPropertyBinder.SetUncontainedNavigationProperty(context, targetEntity, navigationProperty, entities); return(true); } return(false); }
/// <summary> /// 处理关联的实体集合。 /// </summary> /// <param name="queryable"></param> /// <param name="entity"></param> /// <param name="entitySet"></param> /// <param name="property"></param> private void HandleRelationEntitySet(IQueryable queryable, IEntity entity, IEntitySet entitySet, IProperty property) { var added = entitySet.GetAttachedList(); var modified = entitySet.GetModifiedList(); var deleted = entitySet.GetDetachedList(); //处理删除的 if (deleted.Count() > 0) { queryable.BatchOperate(deleted, queryable.CreateDeleteExpression(true)); } //处理修改的 if (modified.Count() > 0) { if (entitySet.AllowBatchUpdate) { queryable.BatchOperate(modified, queryable.CreateUpdateExpression()); } else { foreach (var e in modified) { queryable.UpdateEntity(e); e.SetState(EntityState.Unchanged); HandleRelationProperties(e); } } } //处理新增的 if (added.Count() > 0) { var relation = RelationshipUnity.GetRelationship(property); added.ForEach(e => { foreach (var key in relation.Keys) { var value = entity.GetValue(key.ThisProperty); e.SetValue(key.OtherProperty, value); } }); if (entitySet.AllowBatchInsert) { queryable.BatchOperate(added, queryable.CreateInsertExpression()); } else { foreach (var e in added) { queryable.CreateEntity(e); e.SetState(EntityState.Unchanged); HandleRelationProperties(e); } } } entitySet.Reset(); }
protected DataServiceQueryable(IEntitySet <TBase> entitySet, DataServiceQueryable parent) : base(parent) { this.EntitySet = entitySet; Initialize(); }
/// <summary> /// 转移移除的列表到当前集合中。 /// </summary> /// <param name="source"></param> void IEntitySet.ShiftDetachedList(IEntitySet source) { foreach (var item in source.GetDetachedList()) { detachedList.Add((TEntity)item); } }
/// <summary> /// Gets the first or default entity matching the selection. /// </summary> /// <param name="selection"> /// The selection that identifies the entity. /// </param> /// <typeparam name="T"> /// The type of entity to retrieve. /// </typeparam> /// <returns> /// The first matching <typeparamref name="T"/>, or the default value if no entity is found. /// </returns> private T FirstOrDefaultEntity <T>(IEntitySet selection) { if (selection == null) { throw new ArgumentNullException(nameof(selection)); } var statement = this.DatabaseContext.RepositoryAdapter.CreateSelectionStatement(selection); try { this.DatabaseContext.OpenSharedConnection(); return(this.DatabaseContext.Query <T>(statement, selection.PropertyValues.ToArray()).FirstOrDefault()); } catch (InvalidOperationException ex) { throw new RepositoryException(selection, ex.Message, ex); } catch (DataException ex) { throw new RepositoryException(selection, ex.Message, ex); } catch (DbException ex) { throw new RepositoryException(selection, ex.Message, ex); } }
private static void ReadEntity(Type entityType, IEntitySet target, IDataRecord reader, IServiceLocator factory) { var prototype = factory.Get(entityType) as IEntity; if (prototype == null) { throw new InvalidOperationException($"There is no IEntity implementing object setup for {entityType.Name}"); } if (!prototype.ReadPrimaryKey(reader)) { return; } var entity = target.Find(prototype.PrimaryKeyValue); if (entity == null) { prototype.ReadSelf(reader); target.Add(prototype); entity = prototype; } foreach (var referrenceProperty in entity.GetReferenceProperties()) { var list = entity.OpenProperty(referrenceProperty.Item1); var propReader = reader.GetDeeperReader(referrenceProperty.Item1); ReadEntity(referrenceProperty.Item2, list, propReader, factory); } }
/// <inheritdoc /> public async Task <int> DeleteAsync(IEntitySet entitySet, CancellationToken cancellationToken) { if (entitySet == null) { throw new ArgumentNullException(nameof(entitySet)); } this.CheckDisposed(); var statement = this.DatabaseContext.RepositoryAdapter.CreateDeletionStatement(entitySet); try { await this.DatabaseContext.OpenSharedConnectionAsync(cancellationToken).ConfigureAwait(false); return(await this.DatabaseContext.ExecuteAsync(statement, cancellationToken, entitySet.PropertyValues.ToArray()) .ConfigureAwait(false)); } catch (InvalidOperationException ex) { throw new RepositoryException(entitySet, ex.Message, ex); } catch (DataException ex) { throw new RepositoryException(entitySet, ex.Message, ex); } catch (DbException ex) { throw new RepositoryException(entitySet, ex.Message, ex); } }
/// <inheritdoc /> public int Delete(IEntitySet entitySet) { if (entitySet == null) { throw new ArgumentNullException(nameof(entitySet)); } this.CheckDisposed(); var statement = this.DatabaseContext.RepositoryAdapter.CreateDeletionStatement(entitySet); try { this.DatabaseContext.OpenSharedConnection(); return(this.DatabaseContext.Execute(statement, entitySet.PropertyValues.ToArray())); } catch (InvalidOperationException ex) { throw new RepositoryException(entitySet, ex.Message, ex); } catch (DataException ex) { throw new RepositoryException(entitySet, ex.Message, ex); } catch (DbException ex) { throw new RepositoryException(entitySet, ex.Message, ex); } }
/// <inheritdoc /> public async Task <bool> ContainsAsync(IEntitySet selection, CancellationToken cancellationToken) { if (selection == null) { throw new ArgumentNullException(nameof(selection)); } this.CheckDisposed(); var sql = this.DatabaseContext.RepositoryAdapter.CreateExistsStatement(selection); try { // Always remember to supply this method with an array of values! return(await this.DatabaseContext.ExecuteScalarAsync <int>(sql, cancellationToken, selection.PropertyValues.ToArray()) .ConfigureAwait(false) > 0); } catch (InvalidOperationException ex) { throw new RepositoryException(selection, ex.Message, ex); } catch (DataException ex) { throw new RepositoryException(selection, ex.Message, ex); } catch (DbException ex) { throw new RepositoryException(selection, ex.Message, ex); } }
/// <inheritdoc /> public bool Contains(IEntitySet selection) { if (selection == null) { throw new ArgumentNullException(nameof(selection)); } this.CheckDisposed(); var sql = this.DatabaseContext.RepositoryAdapter.CreateExistsStatement(selection); try { // Always remember to supply this method with an array of values! this.DatabaseContext.OpenSharedConnection(); return(this.DatabaseContext.ExecuteScalar <int>(sql, selection.PropertyValues.ToArray()) > 0); } catch (InvalidOperationException ex) { throw new RepositoryException(selection, ex.Message, ex); } catch (DataException ex) { throw new RepositoryException(selection, ex.Message, ex); } catch (DbException ex) { throw new RepositoryException(selection, ex.Message, ex); } }
public IEntity CreateInEntitySet(IBindableModelContext context, IEntitySet entitySet, ODataEntityDto oDataEntity) { var dependencies = this.dependencyResolver.ResolveDependencies(context, entitySet, entitySet, oDataEntity); var createdEntity = entitySet.CreateEntityInEntitySet(context, dependencies); this.SetPropertyValues(context, entitySet, createdEntity, oDataEntity, dependencies.Keys); return(createdEntity); }
protected void SetPropertyValues( IBindableModelContext context, IEntitySet navigationRoot, IEntity targetEntity, ODataEntityDto oDataEntity) { this.SetPropertyValues(context, navigationRoot, targetEntity, oDataEntity, Enumerable.Empty <string>()); }
IEntitySet <ContentPage> WithRelations(IEntitySet <ContentPage> query) { return(_eventPublisherService.Filter(query.Join <SeoMeta>("Id", "EntityId", additionalExpression: (page, meta) => meta.EntityName == "ContentPage") .Join <User>("UserId", "Id", SourceColumn.Parent) .Relate(RelationTypes.OneToOne <ContentPage, SeoMeta>()) .Relate(RelationTypes.OneToOne <ContentPage, User>()))); }
protected DataLoader(IEntitySet <T> entitySet) { if (entitySet == null) { throw new ArgumentNullException("entitySet"); } this.EntitySet = entitySet; }
/// <summary> /// 检查返回的实体集的值是否为空值。 /// </summary> /// <param name="entitySet"></param> /// <param name="value"></param> /// <returns></returns> internal static PropertyValue CheckReturnEntitySetValue(IEntitySet entitySet, PropertyValue value) { //实体集的 SetClearFlag 为true,认为是设置为 null //var product = new Product (); //product.Orders = null; //此时可以将整个实体集清空 return(entitySet != null && entitySet.IsNeedClear ? PropertyValue.Empty : value); }
/// <inheritdoc /> public int DeleteSelection(IEntitySet entitySet) { if (entitySet == null) { throw new ArgumentNullException(nameof(entitySet)); } return(this.RepositoryProvider.Delete(entitySet as EntitySet <TEntity> ?? entitySet.MapSet <TEntity>())); }
protected virtual void OnDataLoaded(IEntitySet <T> result) { var dataLoaded = DataLoaded; if (dataLoaded != null) { dataLoaded(this, new DataLoadedEventArgs <T>(result)); } }
/// <summary> /// whether an entityset is null or empty /// </summary> /// <param name="obj">obj</param> /// <returns>bool</returns> public static bool IsNullOrEmpty(this IEntitySet obj) { if (obj == null || obj.Id == null || obj.Id.Equals(Guid.Empty)) { return(true); } return(false); }
public ObservableEntityCollection(IEntitySet <T> entitySet, bool reflectChangesOfEntitySet = false) : base((IEnumerable <T>)entitySet ?? new T[0]) { if (entitySet == null) { throw new ArgumentNullException("entitySet"); } this.EntitySet = entitySet; if (reflectChangesOfEntitySet) { this.EntitySet.CollectionChanged += (s, e) => { lock (EntitySet.SyncRoot) { if (!suppressUpdatesFromEntitySet) { suppressUpdatesToEntitySet = true; switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Reset: Clear(); break; default: if (e.OldItems != null) { foreach (T item in e.OldItems) { if (Contains(item)) { Remove(item); } } } if (e.NewItems != null) { foreach (T item in e.NewItems) { if (!Contains(item)) { Add(item); } } } break; } suppressUpdatesToEntitySet = false; } } }; } }
/// <inheritdoc /> public async Task <int> DeleteSelectionAsync(IEntitySet entitySet, CancellationToken cancellationToken) { if (entitySet == null) { throw new ArgumentNullException(nameof(entitySet)); } return(await this.RepositoryProvider.DeleteAsync(entitySet as EntitySet <TEntity> ?? entitySet.MapSet <TEntity>(), cancellationToken) .ConfigureAwait(false)); }
/// <summary> /// The assert selection equality. /// </summary> /// <param name="expected"> /// The expected. /// </param> /// <param name="actual"> /// The actual. /// </param> private static void AssertSetEquality(IEntitySet expected, IEntitySet actual) { if (expected is ISelection expectedSelection && actual is ISelection actualSelection) { var expectedExpressions = expectedSelection.SelectExpressions.Select(expression => expression.AttributeExpression); var actualExpressions = actualSelection.SelectExpressions.Select(expression => expression.AttributeExpression); CollectionAssert.AreEqual( expectedExpressions.Select(expression => $"{expression.GetProperty().PropertyType}.{expression.GetPropertyName()}").ToList(), actualExpressions.Select(expression => $"{expression.GetProperty().PropertyType}.{expression.GetPropertyName()}").ToList()); }
IEntitySet <ContentPage> WithRelations(IEntitySet <ContentPage> query) { Expression <Func <SeoMeta, bool> > seoMetaWhere = meta => meta.EntityName == "ContentPage"; return(query.Join <SeoMeta>("Id", "EntityId") .Join <User>("UserId", "Id", SourceColumn.Parent) .Relate(RelationTypes.OneToOne <ContentPage, SeoMeta>()) .Relate(RelationTypes.OneToOne <ContentPage, User>()) .Where(seoMetaWhere)); }
public EntitySet(IEntitySet <TEntity> entitySetImpl, IServiceProvider provider) { Implementation = entitySetImpl; _createAgent = provider.ProvideInstance <ICreateDataAgent>(); _updateAgent = provider.ProvideInstance <IUpdateDataAgent>(); _deleteAgent = provider.ProvideInstance <IDeleteDataAgent>(); _bulkCreateAgent = provider.ProvideInstance <IBulkCreateDataAgent>(); _bulkUpdateAgent = provider.ProvideInstance <IBulkUpdateDataAgent>(); _bulkDeleteAgent = provider.ProvideInstance <IBulkDeleteDataAgent>(); }
public static void ReadEntitySet(ReadContext readContext, IEntitySet entitySet) { IEntitySetBinding binding; if (!readContext.Model.TryGetBinding(entitySet, out binding)) { throw new ArgumentException("The specified entity set does not support the expected binding.", nameof(entitySet)); } readContext.SetResult(binding.GetAll()); }
private void InitializeContext() { Events = new BrightstarEntitySet<BrightstarDB.Models.EventFeed.IEvent>(this); Subscribers = new BrightstarEntitySet<BrightstarDB.Models.EventFeed.ISubscriber>(this); Topics = new BrightstarEntitySet<BrightstarDB.Models.EventFeed.ITopic>(this); }
private void InitializeContext() { Characters = new BrightstarEntitySet<BSD_Test7.Models.ICharacter>(this); Credits = new BrightstarEntitySet<BSD_Test7.Models.ICredit>(this); Persons = new BrightstarEntitySet<BSD_Test7.Models.IPerson>(this); Productions = new BrightstarEntitySet<BSD_Test7.Models.IProduction>(this); Roles = new BrightstarEntitySet<BSD_Test7.Models.IRole>(this); }
private void InitializeContext() { PersistentEmails = new BrightstarEntitySet<EmailVisualiser.Data.IPersistentEmail>(this); }
private void InitializeContext() { Events = new BrightstarEntitySet<BSD_Test4.Models.IEvent>(this); Performances = new BrightstarEntitySet<BSD_Test4.Models.IPerformance>(this); Photos = new BrightstarEntitySet<BSD_Test4.Models.IPhoto>(this); Persons = new BrightstarEntitySet<BSD_Test4.Models.IPerson>(this); Productions = new BrightstarEntitySet<BSD_Test4.Models.IProduction>(this); ProductionMembers = new BrightstarEntitySet<BSD_Test4.Models.IProductionMember>(this); Roles = new BrightstarEntitySet<BSD_Test4.Models.IRole>(this); }