Procedura: aggiungere e modificare oggetti con ereditarietà tabella per gerarchia (Entity Framework)

Per questo esempio viene utilizzato il modello EDM (Entity Data Model) progettato nell'argomento Procedura: definire un modello con ereditarietà tabella per gerarchia (Entity Framework).

Per creare un progetto utilizzando il modello di ereditarietà tabella per gerarchia

  1. Creare un progetto di applicazione console e aggiungere riferimenti a System.Data.Entity e System.Runtime.Serialization.

  2. Aggiungere un riferimento alla DLL compilata in base al modello di ereditarietà incluso nell'argomento Procedura: definire un modello con ereditarietà tabella per gerarchia (Entity Framework).

  3. Aggiungere gli schemi inclusi nell'argomento Procedura: definire un modello con ereditarietà tabella per gerarchia (Entity Framework) nella stessa cartella del file eseguibile di SchoolDataClient.

  4. Aggiungere un file di configurazione dell'applicazione con il contenuto illustrato nell'esempio seguente.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <connectionStrings><add name="SchoolDataLibContainer" 
       connectionString=
       "metadata=res://*/SchoolDataLib.csdl|
       res://*/SchoolDataLib.ssdl|
       res://*/SchoolDataLib.msl;provider=System.Data.SqlClient;
       provider connection string=&quot;
       Data Source=localhost;
       Initial Catalog=SchoolData;Integrated Security=True;
       MultipleActiveResultSets=True&quot;" 
       providerName="System.Data.EntityClient" />
      </connectionStrings>
    </configuration>
    

Per aggiungere i nuovi tipi derivati Instructor e Student e modificare il tipo Instructor

  1. Creare un'istanza del contesto dell'oggetto SchoolDataEntities.

  2. Creare una nuova istanza del tipo Instructor e assegnare i dati alle proprietà di Instructor.

  3. Aggiungere la nuova istanza di Instructor all'archivio utilizzando il metodo AddToPeople. Il parametro del metodo AddToPeople è il nome della nuova istanza di Instructor.

  4. Salvare le modifiche.

  5. Creare una nuova istanza del tipo Student e inizializzare le proprietà.

  6. Aggiungere all'archivio e salvare le modifiche.

  7. Creare un oggetto ObjectParameter da utilizzare in una query per un'istanza di Instructor con la proprietà LastName uguale a Griffin.

  8. Testare la query per verificare che nell'archivio sia presente il tipo Instructor con questa proprietà.

  9. Eseguire una query per il tipo Instructor designato e assegnare il tipo a una variabile denominata changeInstructor.

  10. Assegnare la proprietà LastName a Anderson e salvare le modifiche.

Esempio

Nel codice seguente vengono aggiunte nuove istanza del tipo Instructor e del tipo Student. Viene quindi eseguita una query per un tipo Instructor con LastName Griffin e la proprietà LastName viene modificata in Anderson.

Option Explicit On
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml
Imports System.Xml.Linq
Imports System.Text
Imports SchoolDataLib

Module Module1

    Sub Main()
        Try
            Using objectContext As SchoolDataLibContainer =
                                      New SchoolDataLibContainer()
                ' Display departments and administrators.
                For Each dept As Department In objectContext.Departments
                    Console.WriteLine("School: {0} Budget: {1}", _
                            dept.Name, dept.Budget)

                    ' Load associated contact reference if any.
                    dept.AdministratorReference.Load()
                    If dept.Administrator IsNot Nothing Then
                        Console.WriteLine("Administrator: {0} {1}", _
                            dept.Administrator.FirstName, _
                            dept.Administrator.LastName)
                    End If
                Next

                For Each eDept As DeptEngineering In _
                        objectContext.Departments.OfType(Of DeptEngineering)()
                    Console.WriteLine("{0} LabBudget: {1} FiberOp Budget: {2}", _
                        eDept.Name, eDept.LabBudget.ToString(), _
                        eDept.FiberOpticsBudget.ToString())
                Next

                Dim countDept As Integer = 0
                Dim newDept As DeptEngineering = New DeptEngineering()

                For Each dept As Department In objectContext.Departments
                    countDept = countDept + 1
                Next

                newDept.DepartmentID = countDept + 1
                newDept.Name = "Engineering School " + (countDept + 1).ToString()
                newDept.StartDate = DateTime.Now
                newDept.FiberOpticsBudget = 250000.0
                newDept.LabBudget = 400000.0
                newDept.Budget = newDept.FiberOpticsBudget + newDept.LabBudget

                ' Create new contact item to be 
                ' added as school administrator.
                Dim countPerson As Integer = 0
                For Each pers As Person In objectContext.People
                    countPerson = countPerson + 1
                Next

                Dim newAdmin As Administrator = New Administrator()
                newAdmin.PersonID = countPerson + 1
                newAdmin.FirstName = "Tony"
                newAdmin.LastName = "Allen"
                newAdmin.AdminDate = DateTime.Now - New TimeSpan(2000, 0, 0, 0)

                ' Assign the contact to Administrator property.
                newDept.Administrator = newAdmin

                ' Add admin and school to object context.
                objectContext.AddToPeople(newAdmin)
                objectContext.AddToDepartments(newDept)

                objectContext.SaveChanges()
            End Using

        Catch ex As System.Data.MappingException
            Console.WriteLine(ex.ToString())
        Catch ex As System.Data.CommandExecutionException
            Console.WriteLine(ex.ToString())
        Catch ex As System.Data.UpdateException
            Console.WriteLine(ex.ToString())
        End Try

    End Sub
End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SchoolDataLibTPH;
using System.Data.Objects;
namespace SchoolDataLib
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Add new Instructor.
                using (SchoolDataLibContainer objectContext =
                                      new SchoolDataLibContainer())
                {
                    Instructor newInstructor =
                        new Instructor();
                    newInstructor.PersonID =
                            objectContext.People.Count<Person>() + 1;
                    newInstructor.FirstName = "Satomi";
                    newInstructor.LastName = "Hayakawa";

                    newInstructor.HireDate = DateTime.Now;

                    objectContext.AddToPeople(newInstructor);
                    objectContext.SaveChanges();

                    // Add new Student.
                    Student newStudent = new Student();
                    int count = objectContext.People.Count<Person>();
                    newStudent.PersonID = count + 1;
                    newStudent.FirstName = "Uzi";
                    newStudent.LastName = "Hefetz";
                    newStudent.EnrollmentDate = DateTime.Now;


                    objectContext.AddToPeople(newStudent);
                    objectContext.SaveChanges();

                    // Change the last name of an instructor.
                    ObjectParameter param =
                                  new ObjectParameter("p", "Hayakawa");
                    if (0 != objectContext.People.OfType<Instructor>().
                                  Where("it.LastName = @p",
                                  param).Count<Instructor>())
                    {
                        Instructor changeInstructor = 
                              objectContext.People.
                              OfType<Instructor>().Where(
                             "it.LastName = @p", param).First();
                        changeInstructor.LastName = "Anderson";
                        objectContext.SaveChanges();

                    }

                    objectContext.Connection.Close();
                }
            }

            catch (System.Data.MappingException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (System.Data.UpdateException e)
            {
                Console.WriteLine(e.ToString());
            }

        }
    }
}

Vedere anche

Attività

Procedura: definire un modello con ereditarietà tabella per gerarchia (Entity Framework)
Procedura: creare ed eseguire query di oggetto utilizzando l'ereditarietà tabella per gerarchia (Entity Framework)