Udostępnij za pośrednictwem


How to: Add an Object to a Specific Entity Set (Entity Framework)

This topic uses the Entity Data Model (EDM) designed in the topic How to: Define a Model with Multiple Entity Sets per Type (Entity Framework).

To create an application using multiple entity sets per type

  1. Create a console application project and add references to System.Data.Entity and System.Runtime.Serialization.

  2. Add a reference to the dll built from the data model defined in the topic How to: Define a Model with Multiple Entity Sets per Type (Entity Framework).

  3. Add an application configuration file. The following syntax supplies a path to schema metadata and connection string to the server that hosts the data.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="RegionalCustomersEntities" 
         connectionString="metadata=.;
         provider=System.Data.SqlClient;
         provider connection string=&quot;
         Data Source=serverName;
         Initial Catalog=RegionalCustomersMEST;
         Integrated Security=True;
         multipleactiveresultsets=true&quot;" 
         providerName="System.Data.EntityClient" />
  </connectionStrings>

</configuration>

Add Customer and Order Entities to Entity Sets Representing Western Region

The following code creates a new instance of the Customer type and adds it to an entity sets representing the western geographical area.

To add entities of same type to separate entity sets

  1. Create an instance of the type CustomerWest and initialize the CustomerId, Name , and TotalPurchases properties of the customer.

  2. Create an instance of the type OrderWest and initialize the properties of the order.

  3. Assign the customer created in step one to the new order.

  4. Add the instances of CustomerWest and OrderWest to storage using the AddTCustomersWest and AddToOrdersWest methods. These methods are created when the data model is generated by Edmgen.exe.

  5. Create another OrderWest instance named newOrder.

  6. Create an ObjectParameter to be used in a query for the customer created in step one.

  7. Query to find the customer.

  8. Update the TotalPurchases property of the customer by adding newOrder TotalAmount property to the customers TotalPurchases.

  9. Assign the customer to newOrder.

  10. Add newOrder to storage using the AddToOrdersWest method.

Example

Option Explicit On
Module Module1
    Sub Main()
        Try
            Using objCtx As RegionalCustomersEntities = _
                        New RegionalCustomersEntities()

                ' Create a new customer.
                Dim customerWest As New Customer()
                customerWest.CustomerId = _
                         objCtx.CustomersWest.Count() + 1
                customerWest.Name = _
                         "CustomerWest " + _
                              customerWest.CustomerId.ToString()
                customerWest.TotalPurchases = CType(875, Decimal)

                ' Create Order.
                Dim orderWest As New OrderWest()
                orderWest.OrderId = _
                         objCtx.OrdersWest.Count() + 1
                orderWest.OrderTotal = customerWest.TotalPurchases
                orderWest.Tax = _
                         orderWest.OrderTotal * CType(0.07, Decimal)

                orderWest.Customer = customerWest

                ' Add customer and order to object context.
                objCtx.AddToCustomersWest("customerWest)
                objCtx.AddToOrdersWest(orderWest)

                objCtx.SaveChanges()

                ' Add order to existing customer.
                Dim newOrder As New OrderWest
                newOrder.OrderId = objCtx.OrdersWest.Count + 1
                newOrder.OrderTotal = CType(338.0, Decimal)
                newOrder.Tax = newOrder.OrderTotal * CType(0.07, Decimal)

                Dim param As New ObjectParameter("p", 3)
                If Not 0 = objCtx.CustomersWest. _
                      Where("it.CustomerId = @p", param).Count() Then
                    Dim c As Customer = _
                        objCtx.CustomersWest. _
                        Where("it.CustomerId = @p", param).FirstOrDefault()

                    c.TotalPurchases = c.TotalPurchases + newOrder.OrderTotal

                    newOrder.Customer = c
                    objCtx.SaveChanges()

                End If

            End Using
        Catch ex As Exception
            Console.WriteLine(ex.ToString())
        End Try
    End Sub
End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RegionalCustomersModel;
using System.Data.Objects;

namespace ClientRegionalCustomers
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (RegionalCustomersEntities objCtx = 
                           new RegionalCustomersEntities())
                {
                    // Create a new customer.
                    Customer customerWest = new Customer();

                    customerWest.CustomerId =
                        objCtx.CustomersWest.Count<Customer>() + 1;

                    customerWest.Name = 
                        "Customer West " + 
                        customerWest.CustomerId.ToString();

                    customerWest.TotalPurchases = 
                        (decimal)875.00;

                    // Create Order.
                    OrderWest orderWest = new OrderWest();
                    orderWest.OrderId = 
                        objCtx.OrdersWest.Count<OrderWest>() + 1;

                    orderWest.OrderTotal = 
                        customerWest.TotalPurchases;
                    orderWest.Tax = 
                        orderWest.OrderTotal * (decimal).07;

                    orderWest.Customer = customerWest;

                    // Add customer and order to object context.
                    objCtx.AddToCustomersWest(customerWest);
                    objCtx.AddToOrdersWest(orderWest);

                    objCtx.SaveChanges();

                    // Add an order to existing customer.
                    OrderWest newOrder = new OrderWest();
                    newOrder.OrderId =
                        objCtx.OrdersWest.Count<OrderWest>() + 1;
                    newOrder.OrderTotal = (decimal)338.00;
                    newOrder.Tax = 
                               newOrder.OrderTotal * (decimal).07;

                    ObjectParameter param = 
                        new ObjectParameter("p", 3);
                    if (0 != objCtx.CustomersWest.Where(
                        "it.CustomerId = @p",
                         param).Count<Customer>())
                    {
                        Customer c =
                            objCtx.CustomersWest.Where(
                            "it.CustomerId = @p", 
                            param).First<Customer>();

                        c.TotalPurchases =
                            c.TotalPurchases + newOrder.OrderTotal;

                        newOrder.Customer = c;
                        
                        objCtx.SaveChanges();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}

See Also

Tasks

How to: Define a Model with Multiple Entity Sets per Type (Entity Framework)
How to: Create and Execute Object Queries using Multiple Entity Sets per Type (Entity Framework)