コード例 #1
0
        public RepositoryProc()
        {
            var contextManager = ServiceLocator.Current.GetInstance<IContextManager<SimirContext>>()
            as ContextManager<SimirContext>;

            _dbContext = ((IObjectContextAdapter)contextManager.GetContext()).ObjectContext;
        }
コード例 #2
0
		public OperationResponse Execute(ObjectContext context)
		{
			d.ProcessTemplate template = null;

			Processor processor = new Processor().SetResponse(_response)
			#region step #1 get context
			.Then((p) => { _context = (d.SopheonEntities)context; })
			#endregion

			#region step #2 get stuff
			.Then((p) => {
				template = _context.ProcessTemplates.FirstOrDefault(x => x.Id.Equals(_request.TemplateId) || (_request.TemplateId <= 0 && x.Name.Equals(_request.Name)));
				
				p.Evaluate(!(template == null && _request.TemplateId > -1), "Model was not found!");
			})
			#endregion

			#region step #3
			.Then((p) => {
				_response.Subject = template == null ? new Domain.Entities.ProcessTemplate { Id = -1, Name = string.Empty, ProjectCount = 0 } : template.ToDomainModel();
			})
			#endregion
			;

			return _response;
		}
コード例 #3
0
        /// <summary>
        /// Executes the future queries.
        /// </summary>
        /// <param name="context">The <see cref="ObjectContext"/> to run the queries against.</param>
        /// <param name="futureQueries">The future queries list.</param>
        public void ExecuteFutureQueries(ObjectContext context, IList<IFutureQuery> futureQueries)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (futureQueries == null)
                throw new ArgumentNullException("futureQueries");

            // used to call internal methods
            dynamic contextProxy = new DynamicProxy(context);
            contextProxy.EnsureConnection();

            try
            {
                using (var command = CreateFutureCommand(context, futureQueries))
                using (var reader = command.ExecuteReader())
                {
                    foreach (var futureQuery in futureQueries)
                    {
                        futureQuery.SetResult(context, reader);
                        reader.NextResult();
                    }
                }
            }
            finally
            {
                contextProxy.ReleaseConnection();
                // once all queries processed, clear from queue
                futureQueries.Clear();
            }
        }
コード例 #4
0
        public void Cloning_the_interception_context_preserves_contextual_information_but_not_mutable_state()
        {
            var objectContext = new ObjectContext();
            var dbContext = DbContextMockHelper.CreateDbContext(objectContext);

            var interceptionContext = new DbCommandInterceptionContext<string>();
            
            var mutableData = ((IDbMutableInterceptionContext<string>)interceptionContext).MutableData;
            mutableData.SetExecuted("Wensleydale");
            mutableData.SetExceptionThrown(new Exception("Cheez Whiz"));
            mutableData.UserState = new object();

            interceptionContext = interceptionContext
                .WithDbContext(dbContext)
                .WithObjectContext(objectContext)
                .AsAsync()
                .WithCommandBehavior(CommandBehavior.SchemaOnly);

            Assert.Equal(new[] { objectContext }, interceptionContext.ObjectContexts);
            Assert.Equal(new[] { dbContext }, interceptionContext.DbContexts);
            Assert.True(interceptionContext.IsAsync);
            Assert.Equal(CommandBehavior.SchemaOnly, interceptionContext.CommandBehavior);

            Assert.Null(interceptionContext.Result);
            Assert.Null(interceptionContext.OriginalResult);
            Assert.Null(interceptionContext.Exception);
            Assert.Null(interceptionContext.OriginalException);
            Assert.Null(interceptionContext.UserState);
            Assert.False(interceptionContext.IsExecutionSuppressed);
        }
コード例 #5
0
        /// <summary>
        ///     Used a delegate to do the actual creation once an ObjectContext has been obtained.
        ///     This is factored in this way so that we do the same thing regardless of how we get to
        ///     having an ObjectContext.
        ///     Note however that a context obtained from only a connection will have no model and so
        ///     will result in an empty database.
        /// </summary>
        public virtual bool Create(ObjectContext objectContext)
        {
            //Contract.Requires(objectContext != null);

            objectContext.CreateDatabase();
            return true;
        }
コード例 #6
0
 public static List<ExplorerItem> GetSchema(ObjectContext objectContext)
 {
     List<ExplorerItem> source = (from es in GetContainer(objectContext).BaseEntitySets
         where ((es.BuiltInTypeKind == BuiltInTypeKind.EntitySet) && (es.ElementType is EntityType)) && (es.ElementType.FullName != "CodeFirstNamespace.EdmMetadata")
         let et = (EntityType) es.ElementType
         orderby es.Name
         select new ExplorerItem(es.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { DragText = es.Name, ToolTipText = et.Name, IsEnumerable = true, Tag = es.ElementType, Children = (from p in et.Properties select new ExplorerItem(p.Name + " (" + p.TypeUsage.EdmType.Name + (p.Nullable ? "?" : "") + ")", ExplorerItemKind.Property, et.KeyMembers.Contains(p) ? ExplorerIcon.Key : ExplorerIcon.Column) { DragText = p.Name }).Concat<ExplorerItem>((from p in et.NavigationProperties
             let fromMany = p.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many
             let toMany = p.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many
             select new ExplorerItem(p.Name, toMany ? ExplorerItemKind.CollectionLink : ExplorerItemKind.ReferenceLink, (!fromMany || !toMany) ? ((fromMany || toMany) ? ((!fromMany || toMany) ? ExplorerIcon.OneToMany : ExplorerIcon.ManyToOne) : ExplorerIcon.OneToOne) : ExplorerIcon.ManyToMany) { ToolTipText = p.ToEndMember.GetEntityType().Name, Tag = p.ToEndMember.GetEntityType() })).ToList<ExplorerItem>() }).ToList<ExplorerItem>();
     foreach (ExplorerItem item in source)
     {
         using (IEnumerator<ExplorerItem> enumerator2 = (from c in item.Children
             where c.Tag != null
             select c).GetEnumerator())
         {
             ExplorerItem child;
             while (enumerator2.MoveNext())
             {
                 child = enumerator2.Current;
                 child.HyperlinkTarget = source.FirstOrDefault<ExplorerItem>(r => r.Tag == child.Tag);
             }
         }
     }
     return source.ToList<ExplorerItem>();
 }
コード例 #7
0
        public void Multiple_contexts_can_be_combined_together()
        {
            var objectContext1 = new ObjectContext();
            var context1 = CreateDbContext(objectContext1);
            var objectContext2 = new ObjectContext();
            var context2 = CreateDbContext(objectContext2);

            var interceptionContext1 = new DbInterceptionContext()
                .WithDbContext(context1)
                .WithDbContext(context2)
                .WithObjectContext(objectContext1);

            var interceptionContext2 = interceptionContext1
                .WithDbContext(context2)
                .WithObjectContext(objectContext1)
                .WithObjectContext(objectContext2);

            var combined = DbInterceptionContext.Combine(new[] { interceptionContext1, interceptionContext2 });

            Assert.Equal(2, combined.DbContexts.Count());
            Assert.Equal(2, combined.ObjectContexts.Count());

            Assert.Contains(context1, combined.DbContexts);
            Assert.Contains(context2, combined.DbContexts);
            Assert.Contains(objectContext1, combined.ObjectContexts);
            Assert.Contains(objectContext2, combined.ObjectContexts);
        }
コード例 #8
0
ファイル: EntityHelper.cs プロジェクト: mbsky/myextensions
 public static bool TryGetEntityType(ObjectContext context, Type clrType, out EntityType entityType)
 {
     entityType = null;
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if (clrType == null)
     {
         throw new ArgumentNullException("clrType");
     }
     EdmType type = null;
     bool flag = context.MetadataWorkspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out type);
     if (!flag)
     {
         LoadAssemblyIntoWorkspace(context.MetadataWorkspace, clrType.Assembly);
         flag = context.MetadataWorkspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out type);
     }
     if (flag)
     {
         entityType = (EntityType)context.MetadataWorkspace.GetEdmSpaceType((StructuralType)type);
         return true;
     }
     return false;
 }
コード例 #9
0
        protected override bool CheckIsSequence(ref ObjectContext objectContext)
        {
            var collectionDescriptor = (CollectionDescriptor)objectContext.Descriptor;

            // If the dictionary is pure, we can directly output a sequence instead of a mapping
            return collectionDescriptor.IsPureCollection || collectionDescriptor.HasOnlyCapacity;
        }
コード例 #10
0
        private static IEnumerable<AuditLog> GetAuditLogs(DbEntityEntry entityEntry, string userName, EntityState entityState, ObjectContext objectContext,
            DateTime auditDateTime)
        {
            var returnValue = new List<AuditLog>();
            var keyRepresentation = BuildKeyRepresentation(entityEntry, KeySeperator, objectContext);

            var auditedPropertyNames = GetDeclaredPropertyNames(entityEntry.Entity.GetType(), objectContext.MetadataWorkspace);
            foreach (var propertyName in auditedPropertyNames)
            {
                var currentValue = Convert.ToString(entityEntry.CurrentValues.GetValue<object>(propertyName));
                var originalValue = Convert.ToString(entityEntry.GetDatabaseValues().GetValue<object>(propertyName));
                if (entityState == EntityState.Modified)
                    if (originalValue == currentValue) //Values are the same, don't log
                        continue;
                returnValue.Add(new AuditLog
                {
                    KeyNames = keyRepresentation.Key,
                    KeyValues = keyRepresentation.Value,
                    OriginalValue = entityState != EntityState.Added
                        ? originalValue
                        : null,
                    NewValue = entityState == EntityState.Modified || entityState == EntityState.Added
                        ? currentValue
                        : null,
                    ColumnName = propertyName,
                    EventDateTime = auditDateTime,
                    EventType = entityState.ToString(),
                    UserName = userName,
                    TableName = entityEntry.Entity.GetType().Name
                });
            }
            return returnValue;
        }
コード例 #11
0
		public OperationResponse Execute(ObjectContext context)
		{
			d.ProcessTemplate template = null;

			Processor processor = new Processor().SetResponse(_response)
			#region step #1 get context
			.Then((p) => { _context = (d.SopheonEntities)context; })
			#endregion

			#region step #2 get stuff
			.Then((p) =>
			{
				template = _context.ProcessTemplates.FirstOrDefault(x => x.Id.Equals(_request.TemplateId));

				p.Evaluate(!(template == null && _request.TemplateId > -1), "Template was not found.");
			})
			#endregion

			#region step 3#
			.Then((p) =>
			{
				_context.ProcessTemplates.DeleteObject(template);

				_context.SaveChanges();
			});
			#endregion

			return _response;
		}
コード例 #12
0
        public AuditEntryState(ObjectContext objectContext, ObjectStateEntry objectStateEntry)
        {
            if (objectStateEntry == null)
                throw new ArgumentNullException("objectStateEntry");

            if (objectStateEntry.Entity == null)
                throw new ArgumentException("The Entity property is null for the specified ObjectStateEntry.", "objectStateEntry");

            if (objectContext == null)
            {
                throw new ArgumentNullException("objectContext");
            }

            ObjectStateEntry = objectStateEntry;
            ObjectContext = objectContext;
            ObjectType = ObjectContext.GetObjectType(objectStateEntry.Entity.GetType());

            Entity = objectStateEntry.Entity;
            EntityType = objectContext.MetadataWorkspace.GetItems(DataSpace.OSpace).OfType<EntityType>().FirstOrDefault(x => x.Name == ObjectType.Name);
            EntityAccessor = TypeAccessor.GetAccessor(ObjectType);

            AuditEntity = new AuditEntity(objectStateEntry.Entity)
            {
                Action = GetAction(objectStateEntry),
            };
        }
コード例 #13
0
ファイル: Queries.cs プロジェクト: richardrflores/efsamples
        /*
         * Use ObjectQuery(T) Class or ObjectSet<T> on the object context to access data using Entity SQL Builder methods.
         * Both methods requires an instance of type ObjectContext. As a result, Entity SQL Builder methods are not supported
         * on objects of type DbContext.
         */
        public static void RunESQLBuilderExample()
        {
            using (var context = new AdventureWorksEntities())
            {
                System.Console.WriteLine("\nUsing Entity SQL Builder");

                if (context.GetType() == typeof (ObjectContext))
                {
                    // An example of ESQL Builder using an ObjectSet<T> on the ObjectContext
                    // var order = context.CreateObjectSet<SalesOrderHeader>("SalesOrderHeader").Where("it.SalesOrderID = 43661");
                    // System.Console.WriteLine("\nSalesOrderID: {0} \nOrderDate: {1} \nDueDate: {2} \nShipDate: {3}", order.SalesOrderID, order.OrderDate, order.DueDate, order.ShipDate);

                    var objContext = new ObjectContext("name=AdventureWorksEntities");
                    var queryString =
                        @"SELECT VALUE salesOrders FROM AdventureWorksEntities.SalesOrderHeader AS salesOrders";
                    var salesQuery1 = new ObjectQuery<SalesOrderHeader>(queryString, objContext, MergeOption.NoTracking);
                    var salesQuery2 = salesQuery1.Where("it.SalesOrderID = 43661");

                    foreach (var order in salesQuery2)
                    {
                        System.Console.WriteLine("\nSalesOrderID: {0} \nOrderDate: {1} \nDueDate: {2} \nShipDate: {3}",
                                                 order.SalesOrderID, order.OrderDate, order.DueDate, order.ShipDate);
                    }
                }
                else
                {
                    System.Console.WriteLine("\nSorry! Context is not of type ObjectContext. ESQL Builder is not supported.");
                }

            }
        }
コード例 #14
0
 public Picture GetPicture(int id)
 {
     using (ObjectContext context = new ObjectContext(this._connectionString))
     {
         return context.CreateObjectSet<Picture>().Single(x=>x.Id == id);
     }
 }
コード例 #15
0
 public Picture GetPicture(string src)
 {
     using (ObjectContext context = new ObjectContext(this._connectionString))
     {
         return context.CreateObjectSet<Picture>().Single(x=>x.Src == src);
     }
 }
        public void Prepare_returns_a_new_instance()
        {
            var objectQueryExecutionPlanFactory = new ObjectQueryExecutionPlanFactory(
                Common.Internal.Materialization.MockHelper.CreateTranslator<object>());

            var metadataWorkspace = new MetadataWorkspace();
            var edmItemCollection = new EdmItemCollection();
            metadataWorkspace.RegisterItemCollection(edmItemCollection);
            metadataWorkspace.RegisterItemCollection(new ObjectItemCollection());
            var fakeSqlProviderManifest = new FakeSqlProviderServices().GetProviderManifest("2008");
            var storeItemCollection = new StoreItemCollection(FakeSqlProviderFactory.Instance, fakeSqlProviderManifest, "2008");
            metadataWorkspace.RegisterItemCollection(storeItemCollection);
            metadataWorkspace.RegisterItemCollection(new StorageMappingItemCollection(edmItemCollection, storeItemCollection, Enumerable.Empty<XmlReader>()));

            var fakeSqlConnection = new FakeSqlConnection();
            fakeSqlConnection.ConnectionString = "foo";
            var entityConnection = new EntityConnection(metadataWorkspace, fakeSqlConnection, false);

            var objectContext = new ObjectContext(entityConnection);
            var dbExpression = new DbNullExpression(TypeUsage.Create(fakeSqlProviderManifest.GetStoreTypes().First()));
            var dbQueryCommandTree = new DbQueryCommandTree(metadataWorkspace, DataSpace.CSpace,
               dbExpression, validate: false);
            var parameters = new List<Tuple<ObjectParameter, QueryParameterExpression>>();

            var objectQueryExecutionPlan = objectQueryExecutionPlanFactory.Prepare(objectContext, dbQueryCommandTree, typeof(object),
                MergeOption.NoTracking, new Span(), parameters, aliasGenerator: null);

            Assert.NotNull(objectQueryExecutionPlan);
        }
コード例 #17
0
        private static OrgUnit BuildKeywordsWithInternalGenerator(int orgUnitId, ObjectContext objectContext)
        {
            // Fetch orgUnit entity with related data
            var orgUnitSet = objectContext.CreateObjectSet<OrgUnit>()
                .Include("OrgUnitServices.Service")
                .Include("OrgUnitTypeAssociations.OrgUnitType");

            var orgUnit = orgUnitSet.Single(o => o.Id == orgUnitId);

            // Sanitize custom keywords and build generated keywords
            var generatedKeywords = new StringBuilder();
            var delimiter = Utils.Common.Keywords.KeywordUtils.ResolveKeywordDelimiter(orgUnit.CustomKeywords);

            orgUnit.CustomKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(orgUnit.CustomKeywords, _excludedWords, delimiter);

            // Append custom keywords
            if (orgUnit.CustomKeywords != null)
                generatedKeywords.Append(orgUnit.CustomKeywords);

            // Append org unit type names
            generatedKeywords.Append(delimiter + String.Join(delimiter, orgUnit.OrgUnitTypeAssociations.Select(t => t.OrgUnitType.Name)));

            // Append service names
            generatedKeywords.Append(delimiter + String.Join(delimiter, orgUnit.OrgUnitServices.Select(s => s.Service.Name)));

            // Sanitize and persist keywords
            var sanitizedKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(generatedKeywords.ToString(), _excludedWords);

            orgUnit.Keywords = sanitizedKeywords;

            return orgUnit;
        }
コード例 #18
0
        /// <summary>
        ///     Creates a database using the core provider (i.e. ObjectContext.CreateDatabase) or
        ///     by using Code First Migrations <see cref="DbMigrator" /> to create an empty database
        ///     and the perform an automatic migration to the current model.
        /// </summary>
        public virtual void CreateDatabase(
            InternalContext internalContext,
            Func<DbMigrationsConfiguration, DbContext, MigratorBase> createMigrator,
            ObjectContext objectContext)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(createMigrator);
            // objectContext may be null when testing.

            if (internalContext.CodeFirstModel != null
                && _resolver.GetService<Func<MigrationSqlGenerator>>(internalContext.ProviderName) != null)
            {
                if (!_migrationsChecker.IsMigrationsConfigured(internalContext, () => false))
                {
                    var migrator = createMigrator(
                        GetMigrationsConfiguration(internalContext),
                        internalContext.Owner);

                    migrator.Update();
                }
            }
            else
            {
                internalContext.DatabaseOperations.Create(objectContext);
                internalContext.SaveMetadataToDatabase();
            }

            // If the database is created explicitly, then this is treated as overriding the
            // database initialization strategy, so make it as already run.
            internalContext.MarkDatabaseInitialized();
        }
コード例 #19
0
 public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
 {
     var connectionString = ((EntityConnection)db.Connection).StoreConnection.ConnectionString;
     var ds = new DataSet();
     using (var conn = new SqlConnection(connectionString))
     {
         using (var cmd = conn.CreateCommand())
         {
             cmd.CommandText = storedProcedureName;
             cmd.CommandType = CommandType.StoredProcedure;
             if (parameters != null)
             {
                 foreach (var parameter in parameters)
                 {
                     cmd.Parameters.Add(parameter);
                 }
             }
             using (var adapter = new SqlDataAdapter(cmd))
             {
                 adapter.Fill(ds);
             }
         }
     }
     return ds;
 }
コード例 #20
0
        /// <summary>
        /// Finds the associated org units.
        /// </summary>
        /// <param name="objectContext">The object context.</param>
        /// <param name="dto">The DTO.</param>
        /// <returns>An enumerable of the associated Org Unit IDs</returns>
        public static IEnumerable<int> FindAssociatedOrgUnits(ObjectContext objectContext, AssociatedOrgUnitsDto dto)
        {
            List<int> relatedUnits = new List<int>();

            var orgUnitAssociationPublished = objectContext.CreateObjectSet<OrgUnitAssociationPublished>();
            var orgUnitPublished = objectContext.CreateObjectSet<OrgUnitPublished>();

            if (dto.OrganizationalUnitId.HasValue)
            {
                var orgUnitIdAsList = new List<int>() { dto.OrganizationalUnitId.Value };

                if (dto.DescendantOption != DescendantOption.NoDescendants)
                {
                    var newUnits = GetDescendants(orgUnitIdAsList, dto.DescendantOption, orgUnitAssociationPublished, orgUnitPublished);
                    AddUnitsToList(ref relatedUnits, newUnits);
                }

                if (dto.LinkedOption != LinkedOption.NoLinkedUnits)
                {
                    var newUnits = GetLinkedUnits(orgUnitIdAsList, dto.LinkedOption, orgUnitAssociationPublished, orgUnitPublished);
                    AddUnitsToList(ref relatedUnits, newUnits);
                }

                //add the current org unit
                AddUnitsToList(ref relatedUnits, new List<int> { dto.OrganizationalUnitId.Value });
            }
            return relatedUnits.ToArray();
        }
コード例 #21
0
        public DbContextWrapper(DbContext context)
        {
            Context = context;

            objectContext = ((IObjectContextAdapter) context).ObjectContext;
            objectContext.ObjectMaterialized += ObjectMaterializedHandler;
        }
コード例 #22
0
		protected override void ReadMember(ref ObjectContext objectContext)
		{
            if (CheckIsSequence(ref objectContext))
			{
                ReadCollectionItems(ref objectContext);
			}
			else
			{
                var keyEvent = objectContext.Reader.Peek<Scalar>();
				if (keyEvent != null)
				{
                    if (keyEvent.Value == objectContext.Settings.SpecialCollectionMember)
					{
                        var reader = objectContext.Reader;
						reader.Parser.MoveNext();

						// Read inner sequence
						reader.Expect<SequenceStart>();
                        ReadCollectionItems(ref objectContext);
						reader.Expect<SequenceEnd>();
						return;
					}
				}

                base.ReadMember(ref objectContext);
			}
		}
コード例 #23
0
        private static Event BuildKeywordsWithInternalGenerator(int eventId, ObjectContext objectContext)
        {
            // Fetch event entity
            var eventEntity = objectContext.CreateObjectSet<Event>().Include("EventTopicAssociations.EventTopic").Single(e => e.Id == eventId);

            // Sanitize custom keywords and build generated keywords
            var generatedKeywords = new StringBuilder();
            var delimiter = Utils.Common.Keywords.KeywordUtils.ResolveKeywordDelimiter(eventEntity.CustomKeywords);

            eventEntity.CustomKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(eventEntity.CustomKeywords, _excludedWords, delimiter);

            // Append custom keywords
            if (eventEntity.CustomKeywords != null)
                generatedKeywords.Append(eventEntity.CustomKeywords);

            // Append event topics
            if (eventEntity.EventTopicAssociations.Count() > 0)
                generatedKeywords.Append(delimiter + string.Join(",", eventEntity.EventTopicAssociations.Select(e => e.EventTopic.Name).ToArray()));

            // Sanitize and persist keywords
            var sanitizedKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(generatedKeywords.ToString(), _excludedWords);

            eventEntity.Keywords = sanitizedKeywords;

            return eventEntity;
        }
コード例 #24
0
        /// <summary>
        /// Validates the user integration entity.
        /// </summary>
        /// <param name="userIntegration">The user integration.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public static StatusMessage ValidateUserIntegrationEntity(UserIntegrationDto userIntegration, ObjectContext context)
        {
            const int maximumExternalIdLength = 50;
            const int maximumExternalSystemLength = 500;

            if (userIntegration == null)
            {
                return StatusMessage.MissingData;
            }
            if (userIntegration.UserId == 0)
            {
                return StatusMessage.InvalidData;
            }
            if (string.IsNullOrEmpty(userIntegration.ExternalId) || userIntegration.ExternalId.Length > maximumExternalIdLength)
            {
                return StatusMessage.InvalidData;
            }
            if (string.IsNullOrEmpty(userIntegration.ExternalSystem) || userIntegration.ExternalSystem.Length > maximumExternalSystemLength)
            {
                return StatusMessage.InvalidData;
            }
            if (context.CreateObjectSet<DAL.UserIntegration>().Count(u => u.UserId == userIntegration.UserId && u.ExternalSystem == userIntegration.ExternalSystem && u.Id != userIntegration.Id) > 0)
            {
                return StatusMessage.DuplicateData;
            }

            return StatusMessage.Success;
        }
コード例 #25
0
        /// <summary>
        ///     Used a delegate to do the actual creation once an ObjectContext has been obtained.
        ///     This is factored in this way so that we do the same thing regardless of how we get to
        ///     having an ObjectContext.
        ///     Note however that a context obtained from only a connection will have no model and so
        ///     will result in an empty database.
        /// </summary>
        public virtual bool Create(ObjectContext objectContext)
        {
            DebugCheck.NotNull(objectContext);

            objectContext.CreateDatabase();
            return true;
        }
コード例 #26
0
        /// <inheritdoc/>
        public override void Initialize(ObjectContext context)
        {
            base.Initialize(context);
            var connection = ((EntityConnection)ObjectContext.Connection).StoreConnection;

            Initialize(connection);
        }
コード例 #27
0
        protected override void ReadMember(ref ObjectContext objectContext)
        {
            var dictionaryDescriptor = (DictionaryDescriptor)objectContext.Descriptor;

            if (dictionaryDescriptor.IsPureDictionary)
            {
                ReadDictionaryItems(ref objectContext);
            }
            else if (objectContext.Settings.SerializeDictionaryItemsAsMembers && dictionaryDescriptor.KeyType == typeof(string))
            {
                // Read dictionaries that can be serialized as items
                string memberName;
                if (!TryReadMember(ref objectContext, out memberName))
                {
                    var value = ReadMemberValue(ref objectContext, null, null, dictionaryDescriptor.ValueType);
                    dictionaryDescriptor.AddToDictionary(objectContext.Instance, memberName, value);
                }
            }
            else
            {
                var keyEvent = objectContext.Reader.Peek<Scalar>();
                if (keyEvent != null && keyEvent.Value == objectContext.Settings.SpecialCollectionMember)
                {
                    var reader = objectContext.Reader;
                    reader.Parser.MoveNext();

                    reader.Expect<MappingStart>();
                    ReadDictionaryItems(ref objectContext);
                    reader.Expect<MappingEnd>();
                    return;
                }

                base.ReadMember(ref objectContext);
            }
        }
コード例 #28
0
        public void WriteYaml(ref ObjectContext objectContext)
        {
            var value = objectContext.Instance;
            var typeOfValue = value.GetType();

            var context = objectContext.SerializerContext;

            var isSchemaImplicitTag = context.Schema.IsTagImplicit(objectContext.Tag);
            var scalar = new ScalarEventInfo(value, typeOfValue)
                {
                    IsPlainImplicit = isSchemaImplicitTag,
                    Style = ScalarStyle.Plain,
                    Anchor = objectContext.Anchor,
                    Tag = objectContext.Tag,
                };

            // Parse default types
            switch (Type.GetTypeCode(typeOfValue))
            {
                case TypeCode.Object:
                case TypeCode.String:
                case TypeCode.Char:
                    scalar.Style = ScalarStyle.Any;
                    break;
            }

            scalar.RenderedValue = ConvertTo(ref objectContext);

            // Emit the scalar
            WriteScalar(ref objectContext, scalar);
        }
コード例 #29
0
        /// <summary>
        /// Removes specified data object.
        /// </summary>
        /// <param name="context">ObjectContext object</param>
        /// <param name="obj">Data object to remove</param>
        /// <returns>
        /// entity set name
        /// </returns>
        public static void RemoveObject(ObjectContext context,
            DataObject obj)
        {
            Debug.Assert(context != null);

            context.DeleteObject(DataObjectHelper.GetEntityObject(obj));
        }
コード例 #30
0
 public PersonPageInfo GetPersonPageInfo()
 {
     using (ObjectContext context = new ObjectContext(_connectionString))
     {
         return context.CreateObjectSet<PersonPageInfo>().FirstOrDefault(x => x.Id == 1);
     }
 }
コード例 #31
0
 private Result InsertData(ObjectContext context)
 {
     context.db.From("cq_pk_bonus").Insert(this.data).ExecuteNotResult();
     return(Success());
 }
コード例 #32
0
        public EntityDataReader(IEnumerable <T> col, EntityDataReaderOptions options, ObjectContext objectContext)
        {
            this.enumerator = col.GetEnumerator();
            this.options    = options;

            if (options.RecreateForeignKeysForEntityFrameworkEntities && objectContext == null)
            {
                throw new ArgumentException("If RecreateForeignKeysForEntityFrameworkEntities=true then objectContext is required");
            }

            //done without a lock, so we risk running twice
            if (scalarAttributes == null)
            {
                scalarAttributes = DiscoverScalarAttributes(typeof(T));
            }
            if (options.FlattenRelatedObjects && scalarAttributesPlusRelatedObjectScalarAttributes == null)
            {
                var atts = DiscoverRelatedObjectScalarAttributes(typeof(T));
                scalarAttributesPlusRelatedObjectScalarAttributes = atts.Concat(scalarAttributes).ToList();
            }
            if (options.RecreateForeignKeysForEntityFrameworkEntities && scalarAttributesPlusRelatedObjectKeyAttributes == null)
            {
                var atts = DiscoverRelatedObjectKeyAttributes(typeof(T), objectContext);
                scalarAttributesPlusRelatedObjectKeyAttributes = atts.Concat(scalarAttributes).ToList();
            }

            if (options.FlattenRelatedObjects)
            {
                attributes = scalarAttributesPlusRelatedObjectScalarAttributes;
            }
            else if (objectContext != null)
            {
                attributes = scalarAttributesPlusRelatedObjectKeyAttributes;
            }
            else
            {
                attributes = scalarAttributes;
            }
        }
コード例 #33
0
 protected override Result <T> ExecuteCore(ObjectContext context)
 {
     return(Success(this.GetData(context)));
 }
コード例 #34
0
 protected override void ValidateCore(ObjectContext context)
 {
     this.current_page = this.current_page ?? 1;
     this.page_size    = this.page_size ?? context.GetPageSize();
 }
コード例 #35
0
        // <summary>
        // Initializes a new query EntitySqlQueryState instance.
        // </summary>
        // <param name="commandText"> The Entity-SQL text of the query </param>
        // <param name="expression">
        // Optional <see cref="DbExpression" /> that defines the query. Must be semantically equal to the
        // <paramref name="commandText" />.
        // </param>
        // <param name="context"> The ObjectContext containing the metadata workspace the query was built against, the connection on which to execute the query, and the cache to store the results in. Must not be null. </param>
        internal EntitySqlQueryState(
            Type elementType, string commandText, DbExpression expression, bool allowsLimit, ObjectContext context,
            ObjectParameterCollection parameters, Span span,
            ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory = null)
            : base(elementType, context, parameters, span)
        {
            Check.NotEmpty(commandText, "commandText");

            _queryText       = commandText;
            _queryExpression = expression;
            _allowsLimit     = allowsLimit;
            _objectQueryExecutionPlanFactory = objectQueryExecutionPlanFactory ?? new ObjectQueryExecutionPlanFactory();
        }
コード例 #36
0
 // <summary>
 // Initializes a new query EntitySqlQueryState instance.
 // </summary>
 // <param name="commandText"> The Entity-SQL text of the query </param>
 // <param name="context"> The ObjectContext containing the metadata workspace the query was built against, the connection on which to execute the query, and the cache to store the results in. Must not be null. </param>
 internal EntitySqlQueryState(
     Type elementType, string commandText, bool allowsLimit, ObjectContext context, ObjectParameterCollection parameters, Span span)
     : this(elementType, commandText, /*expression*/ null, allowsLimit, context, parameters, span)
 {
 }
コード例 #37
0
 protected override Result ExecuteCore(ObjectContext context)
 {
     return(this.InsertData(context));
 }
コード例 #38
0
 public object GetObjectByReference(ObjectContext context, Type type, string raw)
 {
     throw new NotImplementedException();
 }
コード例 #39
0
    public static string GetTableName <T>(this DbContext context) where T : class
    {
        ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;

        return(objectContext.GetTableName <T>());
    }
コード例 #40
0
 protected override void OnExecutingCore(ObjectContext context)
 {
     //this.data.create_time = DateTime.Now;
     //this.data.update_time = DateTime.Now;
     //this.data.id = Guid.NewGuid().ToString().Replace("-", "");
 }
コード例 #41
0
        /// <summary>
        /// Get unproxied entity type
        /// </summary>
        /// <remarks> If your Entity Framework context is proxy-enabled,
        /// the runtime will create a proxy instance of your entities,
        /// i.e. a dynamically generated class which inherits from your entity class
        /// and overrides its virtual properties by inserting specific code useful for example
        /// for tracking changes and lazy loading.
        /// </remarks>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Type GetUnproxiedEntityType(this BaseEntity entity)
        {
            var userType = ObjectContext.GetObjectType(entity.GetType());

            return(userType);
        }
コード例 #42
0
 public string GetReferenceForObject(ObjectContext context, object model)
 {
     throw new NotImplementedException();
 }
 public EarthContext(ObjectContext objectContext)
     : base(objectContext, dbContextOwnsObjectContext: true)
 {
     Configuration.LazyLoadingEnabled = true;
 }
コード例 #44
0
 internal EntityDataSourceChangingEventArgs(ObjectContext context, object entity)
 {
     _context = context;
     _entity = entity;
 }
コード例 #45
0
        protected void CheckBoxList1_DataBound(object sender, EventArgs e)
        {
            MetaTable childTable = ChildrenColumn.ChildTable;

            // Comments assume employee/territory for illustration, but the code is generic

            IList         entityList    = null;
            ObjectContext objectContext = null;

            if (Mode == DataBoundControlMode.Edit)
            {
                object entity;
                ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;
                if (rowDescriptor != null)
                {
                    // Get the real entity from the wrapper
                    entity = rowDescriptor.GetPropertyOwner(null);
                }
                else
                {
                    entity = Row;
                }

                // Get the collection of territories for this employee and make sure it's loaded
                RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;
                if (entityCollection == null)
                {
                    throw new InvalidOperationException(String.Format("The ManyToMany template does not support the collection type of the '{0}' column on the '{1}' table.", Column.Name, Table.Name));
                }
                if (!entityCollection.IsLoaded)
                {
                    entityCollection.Load();
                }

                // Get an IList from it (i.e. the list of territories for the current employee)
                // REVIEW: we should be using EntityCollection directly, but EF doesn't have a
                // non generic type for it. They will add this in vnext
                entityList = ((IListSource)entityCollection).GetList();

                // Get the current ObjectContext
                // REVIEW: this is quite a dirty way of doing this. Look for better alternative
                ObjectQuery objectQuery = (ObjectQuery)entityCollection.GetType().GetMethod(
                    "CreateSourceQuery").Invoke(entityCollection, null);
                objectContext = objectQuery.Context;
            }

            // Go through all the territories (not just those for this employee)
            foreach (object childEntity in childTable.GetQuery(objectContext))
            {
                MetaTable actualTable = MetaTable.GetTable(childEntity.GetType());
                // Create a checkbox for it
                ListItem listItem = new ListItem(
                    actualTable.GetDisplayString(childEntity),
                    actualTable.GetPrimaryKeyString(childEntity));

                // Make it selected if the current employee has that territory
                if (Mode == DataBoundControlMode.Edit)
                {
                    listItem.Selected = entityList.Contains(childEntity);
                }

                CheckBoxList1.Items.Add(listItem);
            }
        }
コード例 #46
0
 internal static IEnumerable <NavigationProperty> GetRequiredNavigationPropertiesForType(this IObjectContextAdapter context, Type entityType)
 {
     return(context.GetNavigationPropertiesForType(ObjectContext.GetObjectType(entityType))
            .Where(navigationProperty => navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One));
 }
コード例 #47
0
 public Audit(ObjectContext context)
 {
     auditingMateus = new AuditingMateus();
     _context       = context;
 }
コード例 #48
0
ファイル: RoutingSerializer.cs プロジェクト: vol16bit/xenko
        public sealed override void WriteYaml(ref ObjectContext objectContext)
        {
            var serializer = serializerSelector.GetSerializer(objectContext.SerializerContext, objectContext.Descriptor);

            serializer.WriteYaml(ref objectContext);
        }
コード例 #49
0
 public static void SetEmpRef(this ObjectContext objectContext, string empRef)
 {
     objectContext.Set(Constants.ObjectContextKeys.EmpRef, empRef);
 }
 public AddDocumentMetadataDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext)
 {
 }
コード例 #51
0
 public static IEnumerable <long> ProcessingSubmissionIds(this ObjectContext objectContext)
 {
     return(objectContext.GetAll <ProcessingSubmissionId>().Select(s => s.SubmissionId));
 }
コード例 #52
0
 public static string GetEmpRef(this ObjectContext objectContext)
 {
     return(objectContext.Get <string>(Constants.ObjectContextKeys.EmpRef));
 }
 public void Borrar(ObjectContext contexto, SaveOptions saveOptions)
 {
     contexto.DeleteObject(this);
     contexto.SaveChanges(saveOptions);
 }
コード例 #54
0
 public static IDictionary <long, DateTime?> ProcessingSubmissionIdsDictionary(this ObjectContext objectContext)
 {
     return(objectContext.GetAll <ProcessingSubmissionId>().ToDictionary(s => s.SubmissionId, s => s.SubmissionDate));
 }
コード例 #55
0
        /// <inheritdoc/>
        public virtual object ReadCollectionItem(ref ObjectContext objectContext, object value, Type itemType, int index)
        {
            var itemObjectContext = new ObjectContext(objectContext.SerializerContext, value, objectContext.SerializerContext.FindTypeDescriptor(itemType));

            return(ReadYaml(ref itemObjectContext));
        }
 public void Guardar(ObjectContext contexto)
 {
     this.Guardar(contexto, System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
 }
コード例 #57
0
 /// <inheritdoc/>
 public virtual string ReadMemberName(ref ObjectContext objectContext, string memberName, out bool skipMember)
 {
     skipMember = false;
     return(memberName);
 }
コード例 #58
0
 protected AbpZeroTenantDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
     : base(objectContext, dbContextOwnsObjectContext)
 {
 }
コード例 #59
0
 protected void WriteYaml(ref ObjectContext objectContext)
 {
     objectContext.SerializerContext.Serializer.ObjectSerializer.WriteYaml(ref objectContext);
 }
コード例 #60
0
        /// <inheritdoc/>
        public virtual object ReadMemberValue(ref ObjectContext objectContext, IMemberDescriptor memberDescriptor, object memberValue, Type memberType)
        {
            var memberObjectContext = new ObjectContext(objectContext.SerializerContext, memberValue, objectContext.SerializerContext.FindTypeDescriptor(memberType));

            return(ReadYaml(ref memberObjectContext));
        }