Condividi tramite


Application Code with AssociationSetMapping (Entity Framework)

The application code in this section illustrates how stored procedures that add or delete instances of associations are used by the Entity Framework. The object model and stored procedures used in the example are described in Mapping Association Sets to Stored Procedures (Entity Framework).

Two basic code sequences are used to add and delete associations between existing entities.

  • Call Add on the EntityCollection specified by a NavigationProperty on an entity, and specify the related object. This works for one-to-many and many-to-many associations.

  • Set the Value property of EntityReference to the related object. This works for one-to-one and many-to-one associations.

The following code uses the Add method to create new associations between Contact and Address entities.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ContactInformationModel;

namespace ContactAddressModFunc
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ContactInformationEntities objCtx =
                              new ContactInformationEntities())
            {
                 for (int i = 1; i < 11; i++)
                 {
                     Contact contact = new Contact();
                     contact.ContactID = i;
                     contact.FirstName = "Contact " + i.ToString();
                     contact.LastName = "LastName " + i.ToString();

                     Address address = new Address();
                     address.AddressID = i;
                     address.StreetAddress = "Street Address " +
                                                 i.ToString();
                     address.City = "Seattle";

                     objCtx.AddToContacts(contact);
                     objCtx.AddToAddresses(address);
                     contact.Address.Add(address);
                     address.Contact.Add(contact);

                    
                 }
                 objCtx.SaveChanges();

                 foreach (Contact contact in objCtx.Contacts)
                 {
                     Console.WriteLine(contact.LastName);
                     contact.Address.Load();
                     foreach (Address address in contact.Address)
                         Console.WriteLine(address.StreetAddress);
                 }

            }

        }
    }
}

See Also

Tasks

How to: Change Relationships Between Objects (Entity Framework)

Concepts

Stored Procedure Support (Entity Framework)
Adding, Modifying, and Deleting Objects (Entity Framework)