本文整理汇总了C#中ObjectContext类的典型用法代码示例。如果您正苦于以下问题:C# ObjectContext类的具体用法?C# ObjectContext怎么用?C# ObjectContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ObjectContext类属于命名空间,在下文中一共展示了ObjectContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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);
}
示例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;
}
示例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;
}
示例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;
}
示例6: GetPicture
public Picture GetPicture(string src)
{
using (ObjectContext context = new ObjectContext(this._connectionString))
{
return context.CreateObjectSet<Picture>().Single(x=>x.Src == src);
}
}
示例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.");
}
}
}
示例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;
}
示例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);
}
示例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;
}
示例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;
}
示例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);
}
}
示例13: Initialize
/// <inheritdoc/>
public override void Initialize(ObjectContext context)
{
base.Initialize(context);
var connection = ((EntityConnection)ObjectContext.Connection).StoreConnection;
Initialize(connection);
}
示例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));
}
示例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;
}