dotConnect for Salesforce Documentation
In This Topic
    Entity Framework Tutorial
    In This Topic

    This tutorial guides you through the process of creating a simple application powered by ADO.NET Entity Framework. In less than 5 minutes you will have a ready-to-use data access layer for your business objects.

    Please note that this tutorial is not applicable for Entity Framework Core. It is intended for previous Entity Framework versions.

    In this walkthrough:

    Introducing the ADO.NET Entity Framework

    ADO.NET Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework. It is designed to enable developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications.

    Requirements

    In order to connect to Salesforce server you need dotConnect for Salesforce installed and IDE running. ADO.NET Entity Framework requires .NET Framework 3.5 Service Pack 1 or higher and Visual Studio 2008 Service Pack 1 or higher. Note that Entity Framework support is not available in Standard Edition of dotConnect for Salesforce.

    In this tutorial we will use Account and Contact Salesforce objects.

    For Entity Framework 6, you will also need a NuGet Visual Studio extension installed since it is used for adding EntityFramework NuGet package. Alternatively you may create model for Entity Framework v1 or v4, which don't require NuGet, in this tutorial.

    In this sample we will create a simple console application. It could be any other project type as well, but for simplicity's sake we'll use console project throughout the tutorial. Start Visual Studio and create a new console application.

    Entity Framework v6

    The following actions are required if you want to create an Entity Framework v6 model.

    Open the Package Manager Console window and execute the following command in it.

    install-package EntityFramework

    After this add the following line:

    <provider invariantName="Devart.Data.Salesforce" type="Devart.Data.Salesforce.Entity.SalesforceEntityProviderServices, 
    Devart.Data.Salesforce.Entity, Version=3.2.520.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
    

    to the entityFramework -> providers section.

    <entityFramework>
        <providers>
          <provider invariantName="Devart.Data.Salesforce" type="Devart.Data.Salesforce.Entity.SalesforceEntityProviderServices, 
          Devart.Data.Salesforce.Entity, Version=3.2.520.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
        </providers>
    </entityFramework>
    

    Note: replace 3.2.520.0 with the actual assembly version.

    You also need to add the following assemblies to the project references:

    After this you need to rebuild the project before running the EDM wizard.

    Generating Model from Database

    1. In the Solution Explorer right-click on the project and choose Add | New Item.
    2. In the dialog choose ADO.NET Entity Data Model, click Add. This launches Entity Data Model Wizard.
    3. In the wizard choose Generate from database, click Next.
    4. Pick an existing dotConnect for Salesforce connection string or create a new one. When creating a new connection select Salesforce Data Source in the Data Source list, then dotConnect for Salesforce in the Data provider combobox. This step is illustrated in the screenshot below.
    5. Agree to include the sensitive data in the connection string.
    6. In the field Save entity connection settings... type SalesforceEntities. This will be the name of the main data access class. Click Next.
    7. Choose Account and Contact objects that will be used in the model.
    8. Click Finish. The model will be generated and opened in EDM Designer.

    After this, in each added entity click the OwnerID property and set their StoreGeneratedPattern property to Identity in the Properties window. Then open this model in the XML editor (right-click the model in Solution Explorer and select Open With... from the shortcut menu, and then select XML (Text) Editor in the list and click OK. In the XML editor add the 'StoreGeneratedPattern="Identity"' parameter for the Property tag of OwnerID property for all entities in the Storage part.

    The model you've just generated is ready to use. Its name is Model1.edmx, unless you changed it in the step 2. You can inspect it visually in the designer or take a look behind the scenes with XML Editor.

    The wizard creates classes for all selected tables that represent entities. It also creates a descendant of System.Data.Entity.DbContext class (used by default since Visual Studio 2012) or System.Data.Objects.ObjectContext class (used by default in older Visual Studio versions), which controls the connection to the database, and the whole data flow. This class includes properties and methods named after your database objects. You will use these members to retrieve and modify data in the context. The code is contained in an autogenerated file Model1.Designer.cs (Model1.Designer.vb).

    Note that if you have an association between two properties of non-coinciding numeric types, you can manually change both conceptual and storage types to the type that will be wide enough to include data for each property.

    Querying Data

    All Entity Framework operations are executed are executed through a DbContext descendant (default since Visual Studio 2012) or through a ObjectContext descendant, which is named SalesforceEntities in this tutorial. To retrieve data you have to first create an instance of the context, then prepare a query with LINQ to Entities or EntitySQL or their mix, and then access the object returned by the query, which may be a collection of objects or a single object.

    Let's read all the data from the Account object, sort it by it Name, and output some columns. Add the following block of code to the method Main:

    SalesforceEntities context = new SalesforceEntities();
    var query = from it in context.Account
                orderby it.Name
                select it;
    
    foreach (Account a in query)
      Console.WriteLine("{0} | {1} | {2}", a.Name, a.Type, a.Fax);
    
    Console.ReadLine();
    
    Dim context As SalesforceEntities = New SalesforceEntities
    Dim query = From it In context.Account _
        Order By it.Name _
        Select it
    
    Dim a As Account
    For Each a In query
      Console.WriteLine("{0} | {1} | {2}", a.Name, a.Type, a.Fax)
    Next
    
    Console.ReadLine()
    
    

    As simple as that. You prepare a query and then iterate through it as you would do with a usual collection of objects. The database interaction is performed by Entity Framework in the background. Now let's see who is who in this code sample.

    Here is the project's output in the console:

    Note that the LINQ to Entities query code just describes the query. It does not execute it. This approach is known as deferred execution.

    Now let's query data from two Salesforce tables (objects) united with a master-detail relationship. Replace the old code with this:

    SalesforceEntities context = new SalesforceEntities();
    
    var query = from it in context.Contact.Include("Account")
                orderby it.LastName
                select it;
    
    foreach (Contact contact in query)
        Console.WriteLine("{0} | {1} | {2}", 
          contact.Account == null ? "null" : contact.Account.Name, 
          contact.LastName, contact.Phone);
    
    Console.ReadLine();
    
    Dim context As SalesforceEntities = New SalesforceEntities
    Dim query = From it In context.Contact.Include("Account") _
    Order By it.LastName _
    Select it
    
    For Each contact As Contact In query
    	Console.WriteLine("{0} | {1} | {2}", _
        If(contact.Account Is Nothing, "null", contact.Account.Name), _
        contact.LastName, contact.Phone)
    Next
    Console.ReadLine()
    
    

    This sample is much like the previous one, with exception that it adds the Include method that instructs the query to retrieve data from one more table.

    Inserting New Data

    What earlier was adding rows to tables, now is just adding new objects to context collections. When you are ready to send the changes to the database, call the SaveChanges() method of the context. Before doing this, you must first set all properties that do not support null (Nothing) values. The SaveChanges() method generates and executes commands that perform the equivalent INSERT, UPDATE, or DELETE statements against the data source.

    Let's add a new contact and a new account to Salesforce. Replace the old code with this:

    SalesforceEntities context = new SalesforceEntities();
    
    // Create a new account
    Account newAccount = new Account();
    newAccount.Name = "new account";
    newAccount.Type = "Customer - Direct";
    context.AddToAccount(newAccount);
    
    // Create a new contact
    Contact newContact = new Contact();
    newContact.LastName = "new contact";
    
    // Associate the new contact with the new account
    newContact.Account = newAccount;
    context.AddToContact(newContact);
    
    // Send the changes to the database.
    // Until you do it, the changes are cached on the client side.
    context.SaveChanges();
    
    // Request the new contact from the database
    var query = from it in context.Contact.Include("Account")
                where it.LastName == "new contact"
                select it;
    
    // Since we query for a single object instead of a collection, we can use the method First()
    Contact contact = query.First();
    Console.WriteLine("{0} | {1} ",
      contact.Account.Name, contact.LastName);
    Console.ReadLine();
    
    Dim context As SalesforceEntities = New SalesforceEntities
    
    ' Create a new account
    Dim newAccount As Account = New Account()
    newAccount.Name = "new account"
    newAccount.Type = "Customer - Direct"
    context.AddToAccount(newAccount)
    
    ' Create a new contact
    Dim newContact As Contact = New Contact()
    newContact.LastName = "new contact"
    
    ' Associate the new contact with the new account
    newContact.Account = newAccount
    context.AddToContact(newContact)
    
    ' Send the changes to the database.
    ' Until you do it, the changes are cached on the client side.
    context.SaveChanges()
    
    ' Request the new contact from the database
    Dim query = From it in context.Contact.Include("Account") _
                Where it.LastName = "new contact" _
                Select it
    
    ' Since we query for a single object instead of a collection, we can use the method First()
    Dim contact As Contact = query.First()
    Console.WriteLine("{0} | {1}", _
      contact.Account.Name, contact.LastName)
    Console.ReadLine()
    
    

    The methods AddToAccount, AddToContact, and others are automatically generated in the context. Such methods exist for every class in your model.

    Note that after you have added the new contact and account by submitting the changes, you cannot execute this solution again as is. To execute the solution again, change the names and IDs of the objects to be added.

    Updating Data

    Entity instances are modified as usual. The only thing to remember is that you have to invoke the SaveChanges() method to send the data to the database.

    Append the following block to the existing code and launch the project:

    contact.LastName = "Edited contact";
    context.SaveChanges();
    
    contact.LastName = "Edited contact"
    context.SaveChanges()
    
    

    Deleting Data

    To extract an instance from a context use the DeleteObject method of the context. The object is removed from the collection of its type, but not destroyed. To delete the object's data from the database invoke the SaveChanges() method.

    You can do this with a block of code like the following:

    context.DeleteObject(newAccount);
    context.DeleteObject(newContact);
    context.SaveChanges();
    
    context.DeleteObject(newAccount)
    context.DeleteObject(newContact)
    context.SaveChanges()
    
    

    Additional Information

    Now that you can perform the basic data manipulation with Entity Framework, you can move on to some advanced topics.

    We recommend you to use Entity Developer (Devart Entity Model, *.edml) instead of EDM Designer (ADO.NET Entity Data Model, *.edmx) because it is adjusted for working with Salesforce and has an advanced functionality. Additionally, Entity Developer adds registration of EF6 provider in app.config automatically and offers designer (Database First / Model First) for EF Core.

    Here are some useful links to MSDN:

    For hands-on experience download the separate Entity Framework Query Samples (EF1/EF4/EF5/EF6) package or use samples shipped with dotConnect for Salesforce. You can access the samples from the Start menu.

    To understand deeper the works of Entity Framework engine you can watch the generated SQL statements in dbMonitor.

    See Also

    Entity Framework section  | Entity Framework Support Overview