Export (0) Print
Expand All
2 out of 6 rated this helpful - Rate this topic

Working with ObjectSet

.NET Framework 4

In the .NET Framework version 3.5 SP1, an ObjectContext class for a specific model typically has a set of properties of type ObjectQuery that represent queries on specific entity sets. The ObjectContext also has methods for adding, deleting, attaching, and updating objects. These methods usually take an object and a string parameter that specifies the entity set name. In the .NET Framework version 4, an ObjectContext class for a specific model has instead properties of type ObjectSet that represent the model’s entity sets. The CreateObjectSet method and its overloads creates a new ObjectSet instance. In the .NET Framework version 4, we recommend that you use methods on the ObjectSet object to perform create, read, delete, attach, and update operations. ObjectSet derives from ObjectQuery, so it also works as a query object.

In versions starting with .NET Framework version 4, you can use the following methods defined on ObjectSet instead of the equivalent ones defined on ObjectContext:

AddObject

Attach

ApplyCurrentValues

ApplyOriginalValues

DeleteObject

Detach

For example, in .NET Framework 4, use the following code:

using (AdventureWorksEntities context =

new AdventureWorksEntities())

{

// Add the new object to the context.

context.Products.AddObject(newProduct);

}

In .NET Framework 3.5 SP1, use the following code:

using (AdventureWorksEntities context =

new AdventureWorksEntities())

{

// Add the new object to the context.

context.AddObject("Products", newProduct);

}

The following example demonstrates how to use a non-typed ObjectContext to create an ObjectSet instance.

// Create the ObjectContext.
ObjectContext context =
    new ObjectContext("name=AdventureWorksEntities");

ObjectSet<Product> query = context.CreateObjectSet<Product>();

// Iterate through the collection of Products.
foreach (Product result in query)
    Console.WriteLine("Product Name: {0}", result.Name);

The ObjectSet class implements the IObjectSet interface. The IObjectSet interface may be useful in testing scenarios. To create unit tests that test an application without executing queries at the data source, you can use test objects that are populated in memory with test data. You can define a test ObjectSet type that implements IObjectSet and can store test data outside of the data source. You must also define a test ObjectContext class that exposes the properties of the test IObjectSet type and that has a method that initializes the entity sets with test data.

For examples of the testability improvements in the .NET Framework version 4, see the following blog posts: ADO.NET team blog and Julie Lerman's blog.

See Also

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.