• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ObjectContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ObjectContext的典型用法代码示例。如果您正苦于以下问题:C# ObjectContext类的具体用法?C# ObjectContext怎么用?C# ObjectContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ObjectContext类属于命名空间,在下文中一共展示了ObjectContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Cloning_the_interception_context_preserves_contextual_information_but_not_mutable_state

        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);
        }
开发者ID:Cireson,项目名称:EntityFramework6,代码行数:30,代码来源:DbCommandInterceptionContextTests.cs


示例2: Multiple_contexts_can_be_combined_together

        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);
        }
开发者ID:christiandpena,项目名称:entityframework,代码行数:27,代码来源:DbInterceptionContextTests.cs


示例3: Create

        /// <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;
        }
开发者ID:jimmy00784,项目名称:entityframework,代码行数:14,代码来源:DatabaseOperations.cs


示例4: Execute

		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;
		}
开发者ID:mikedhutchins,项目名称:sopheon.prototype,代码行数:29,代码来源:DeleteTemplateCommand.cs


示例5: CheckIsSequence

        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;
        }
开发者ID:vasily-kirichenko,项目名称:SharpYaml,代码行数:7,代码来源:CollectionSerializer.cs


示例6: GetPicture

 public Picture GetPicture(string src)
 {
     using (ObjectContext context = new ObjectContext(this._connectionString))
     {
         return context.CreateObjectSet<Picture>().Single(x=>x.Src == src);
     }
 }
开发者ID:RomanOrv,项目名称:BlogProject,代码行数:7,代码来源:EFPictureRepository.cs


示例7: RunESQLBuilderExample

        /*
         * 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.");
                }

            }
        }
开发者ID:richardrflores,项目名称:efsamples,代码行数:36,代码来源:Queries.cs


示例8: BuildKeywordsWithInternalGenerator

        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;
        }
开发者ID:rickeygalloway,项目名称:Test,代码行数:26,代码来源:KeywordGenerator.cs


示例9: WriteYaml

        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);
        }
开发者ID:vasily-kirichenko,项目名称:SharpYaml,代码行数:31,代码来源:ScalarSerializerBase.cs


示例10: ValidateUserIntegrationEntity

        /// <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;
        }
开发者ID:rickeygalloway,项目名称:Test,代码行数:34,代码来源:UserIntegrationValidator.cs


示例11: Create

        /// <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;
        }
开发者ID:jwanagel,项目名称:jjwtest,代码行数:14,代码来源:DatabaseOperations.cs


示例12: ReadMember

        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);
            }
        }
开发者ID:Kryptos-FR,项目名称:xenko-reloaded,代码行数:35,代码来源:DictionarySerializer.cs


示例13: Initialize

        /// <inheritdoc/>
        public override void Initialize(ObjectContext context)
        {
            base.Initialize(context);
            var connection = ((EntityConnection)ObjectContext.Connection).StoreConnection;

            Initialize(connection);
        }
开发者ID:jesusico83,项目名称:Telerik,代码行数:8,代码来源:CommitFailureHandler.cs


示例14: RemoveObject

        /// <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));
        }
开发者ID:erindm,项目名称:route-planner-csharp,代码行数:15,代码来源:ContextHelper.cs


示例15: BuildKeywordsWithInternalGenerator

        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;
        }
开发者ID:rickeygalloway,项目名称:Test,代码行数:32,代码来源:KeywordGenerator.cs


示例16: ReadMember

		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);
			}
		}
开发者ID:modulexcite,项目名称:SharpYaml,代码行数:27,代码来源:CollectionSerializer.cs


示例17: GetPersonPageInfo

 public PersonPageInfo GetPersonPageInfo()
 {
     using (ObjectContext context = new ObjectContext(_connectionString))
     {
         return context.CreateObjectSet<PersonPageInfo>().FirstOrDefault(x => x.Id == 1);
     }
 }
开发者ID:RomanOrv,项目名称:HelpForSick,代码行数:7,代码来源:EFPersonPageInfoRepository.cs


示例18: AuditEntryState

        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),
            };
        }
开发者ID:ArthurYiL,项目名称:EntityFramework.Extended,代码行数:26,代码来源:AuditEntryState.cs


示例19: FindAssociatedOrgUnits

        /// <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();
        }
开发者ID:rickeygalloway,项目名称:Test,代码行数:34,代码来源:AssociatedOrgUnitFinder.cs


示例20: GetAuditLogs

        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;
        }
开发者ID:johannbrink,项目名称:EF6Auditing,代码行数:33,代码来源:AuditLogBuilder.cs



注:本文中的ObjectContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ObjectCreateExpression类代码示例发布时间:2022-05-24
下一篇:
C# ObjectContent类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap