Share via


How to: Define a Custom Object Context

When you use POCO entities, you disable object layer generation by the Entity Framework. In addition to defining custom entity types, you need to either define a custom object context type or manage your own connections through a manually created instance of EntityConnection that you pass to the constructor of the ObjectContext. For information about how to create an EntityConnection, see How to: Build an EntityConnection Connection String

This topic demonstrates how to create a custom object context.

Note

To disable object layer generation with the ADO.NET Entity Data Model Designer (Entity Designer), open the .edmx file in the Entity Designer. Right-click on the designer surface and select Properties. In the Properties window, select the Code Generation Strategy property and select None.

The custom object context class manages the POCO entities that are defined in How to: Define POCO Entities.

A custom object context should include the following functionality:

  • The ability to instantiate an ObjectContext that is specific to your conceptual model, including predefined connections.

  • Properties that return type-specific ObjectSet objects.

For information about defining custom entity types, see How to: Define POCO Entities.

To use generated object context code in your custom object context code

  1. Add a class code file to your project.

  2. Include the following namespaces:

    System

    System.Data.Objects

    System.Collections.Generic

  3. Rename the class to POCOAdventureWorksEntities. Make sure the class inherits from the ObjectContext class.

    Partial Public Class POCOAdventureWorksEntities
        Inherits ObjectContext
    
    public partial class POCOAdventureWorksEntities : ObjectContext
    
  4. Define member variables of the ObjectSet type for each POCO entity type:

    Private _contacts As ObjectSet(Of Contact)
    Private _lineItems As ObjectSet(Of LineItem)
    Private _orders As ObjectSet(Of Order)
    
    private ObjectSet<Contact> _contacts;
    private ObjectSet<LineItem> _lineItems;
    private ObjectSet<Order> _orders;
    
  5. Define constructors to the POCOAdventureWorksEntities class.

    Public Sub New()
        MyBase.New("name=AdventureWorksEntities", "AdventureWorksEntities")
        Me.ContextOptions.LazyLoadingEnabled = True
    End Sub
    
    Public Sub New(ByVal connectionString As String)
        MyBase.New(connectionString, "AdventureWorksEntities")
        Me.ContextOptions.LazyLoadingEnabled = True
    End Sub
    
     public POCOAdventureWorksEntities()
         : base("name=AdventureWorksEntities", "AdventureWorksEntities")
     {
         this.ContextOptions.LazyLoadingEnabled = true;
    }
    
     public POCOAdventureWorksEntities(string connectionString)
         : base(connectionString, "AdventureWorksEntities")
     {
         this.ContextOptions.LazyLoadingEnabled = true;
     }
    
  6. Define properties that return ObjectSet objects.

    Public ReadOnly Property Contacts() As ObjectSet(Of Contact)
        Get
            Return If(_contacts, MyBase.CreateObjectSet(Of Contact)())
        End Get
    End Property
    
    Public ReadOnly Property LineItems() As ObjectSet(Of LineItem)
        Get
            Return If(_lineItems, MyBase.CreateObjectSet(Of LineItem)())
        End Get
    End Property
    
    Public ReadOnly Property Orders() As ObjectSet(Of Order)
        Get
            Return If(_orders, MyBase.CreateObjectSet(Of Order)())
        End Get
    End Property
    
    public ObjectSet<Contact> Contacts
    {
        get
        {
            return _contacts ?? (_contacts = base.CreateObjectSet<Contact>());
        }
    }
    
    public ObjectSet<LineItem> LineItems
    {
        get
        {
            return _lineItems ?? (_lineItems = base.CreateObjectSet<LineItem>());
        }
    }
    
    public ObjectSet<Order> Orders
    {
        get
        {
            return _orders ?? (_orders = base.CreateObjectSet<Order>());
        }
    }
    

Example

This example shows the custom object context code that supports the Contact, Order, and LineItem custom data classes.

Partial Public Class POCOAdventureWorksEntities
    Inherits ObjectContext
    Private _contacts As ObjectSet(Of Contact)
    Private _lineItems As ObjectSet(Of LineItem)
    Private _orders As ObjectSet(Of Order)
#Region "Constructors"
    Public Sub New()
        MyBase.New("name=AdventureWorksEntities", "AdventureWorksEntities")
        Me.ContextOptions.LazyLoadingEnabled = True
    End Sub

    Public Sub New(ByVal connectionString As String)
        MyBase.New(connectionString, "AdventureWorksEntities")
        Me.ContextOptions.LazyLoadingEnabled = True
    End Sub
#End Region

#Region "ObjectSet Properties"
    Public ReadOnly Property Contacts() As ObjectSet(Of Contact)
        Get
            Return If(_contacts, MyBase.CreateObjectSet(Of Contact)())
        End Get
    End Property

    Public ReadOnly Property LineItems() As ObjectSet(Of LineItem)
        Get
            Return If(_lineItems, MyBase.CreateObjectSet(Of LineItem)())
        End Get
    End Property

    Public ReadOnly Property Orders() As ObjectSet(Of Order)
        Get
            Return If(_orders, MyBase.CreateObjectSet(Of Order)())
        End Get
    End Property

#End Region
    Public Overloads Overrides Function SaveChanges(ByVal options As SaveOptions) As Integer

        For Each entry As ObjectStateEntry In ObjectStateManager.GetObjectStateEntries(EntityState.Added Or EntityState.Modified)
            ' Validate the objects in the Added and Modified state 
            ' if the validation fails throw an exeption. 
        Next
        Return MyBase.SaveChanges(options)
    End Function

End Class
public partial class POCOAdventureWorksEntities : ObjectContext
{
    private ObjectSet<Contact> _contacts;
    private ObjectSet<LineItem> _lineItems;
    private ObjectSet<Order> _orders;
    #region Constructors
    public POCOAdventureWorksEntities()
        : base("name=AdventureWorksEntities", "AdventureWorksEntities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
   }

    public POCOAdventureWorksEntities(string connectionString)
        : base(connectionString, "AdventureWorksEntities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
    }
    #endregion

    #region ObjectSet Properties
    public ObjectSet<Contact> Contacts
    {
        get
        {
            return _contacts ?? (_contacts = base.CreateObjectSet<Contact>());
        }
    }

    public ObjectSet<LineItem> LineItems
    {
        get
        {
            return _lineItems ?? (_lineItems = base.CreateObjectSet<LineItem>());
        }
    }

    public ObjectSet<Order> Orders
    {
        get
        {
            return _orders ?? (_orders = base.CreateObjectSet<Order>());
        }
    }

    #endregion
    public override int SaveChanges(SaveOptions options)
    {

        foreach (ObjectStateEntry entry in
            ObjectStateManager.GetObjectStateEntries(
            EntityState.Added | EntityState.Modified))
        {
            // Validate the objects in the Added and Modified state
            // if the validation fails throw an exeption.
        }
        return base.SaveChanges(options);
    }

}

See Also

Reference

EDM Generator (EdmGen.exe)

Concepts

Customizing Objects

Other Resources

How to: Customize Object-Layer Code Generation