Cómo agregar un objeto a un conjunto de entidades específico (Entity Framework)

En este tema se usa el Entity Data Model (EDM) definido en el tema Cómo definir un modelo con múltiples conjuntos de entidades por tipo (Entity Framework).

Para crear una aplicación utilizando múltiples conjuntos de entidades por tipo.

  1. Cree un proyecto de aplicación de consola y agregue referencias a System.Data.Entity y System.Runtime.Serialization.

  2. Agregue una referencia a la biblioteca DLL generada con el modelo de datos que se define en el tema Cómo definir un modelo con múltiples conjuntos de entidades por tipo (Entity Framework).

  3. Agregue un archivo de configuración de la aplicación. En la sintaxis siguiente se proporciona una ruta a la cadena de conexión y a los metadatos del esquema para el servidor que hospeda los datos.

<?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>

Agregue las entidades Customer y Order a los conjuntos de entidades que representan el área occidental

El código siguiente crea una nueva instancia del tipo Customer y la agrega a conjuntos de entidades que representan el área geográfica occidental.

Para agregar entidades del mismo tipo a conjuntos de entidades separados

  1. Cree una instancia del tipo CustomerWest e inicialice las propiedades CustomerId, Name y TotalPurchases del cliente.

  2. Cree una instancia del tipo OrderWest e inicialice las propiedads del pedido.

  3. Asigne el cliente creado en el paso uno a un nuevo pedido.

  4. Agregue las instancias de CustomerWest y OrderWest al almacenamiento usando los métodos AddTCustomersWest y AddToOrdersWest. Estos métodos se crean cuando Edmgen.exe genera el modelo de datos.

  5. Cree otra instancia OrderWest llamada newOrder.

  6. Cree un ObjectParameter que se utilizará en una consulta para el cliente creado en el paso uno.

  7. Realice una consulta para buscar el cliente.

  8. Actualice la propiedad TotalPurchases del cliente agregando la propiedad newOrderTotalAmount a TotalPurchases del cliente.

  9. Asigne el cliente a newOrder.

  10. Agregue newOrder al almacenamiento utilizando el método AddToOrdersWest.

Ejemplo

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());
            }
        }
    }
}

Vea también

Tareas

Cómo definir un modelo con múltiples conjuntos de entidades por tipo (Entity Framework)
Cómo crear y ejecutar consultas de objeto con múltiples conjuntos de entidades por tipo (Entity Framework)