Curs EntityFramework

download Curs EntityFramework

of 75

Transcript of Curs EntityFramework

  • 8/16/2019 Curs EntityFramework

    1/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 1

    Entity Framework – teme abordate

     Modele de programare

     Database First;

     Code First.

     Model Design First.

     Entity Data Model –  EDM

     Terminologie EF

     ObjectContext, ObjectSet

     DbContext, DbSet

     EF –  Incarcare date relationate

     Cereri cu DbContext.

     Cereri pe date locale.

     Iterare proprietati de navigare.

     Lazy loading

     Eager loading

     Explicit loading

     Incarcare continut proprietati de navigare tip

    colectie.

     Adaugare, modificare si stergere entitati.

     Entity Framework si aplicatii n-Tier

  • 8/16/2019 Curs EntityFramework

    2/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 2

    Bibliografie 

    MSDNJulia Lerman: SECOND EDITION, Programming Entity

    Framework

    Julia Lerman, Rowan Miller: Programming Entity

    Framework: DbContext

    Brian Driscoll, Nitin Gupta, Rob Vettor, Zeeshan Hirani,

    Larry Tenny : Entity Framework 6 Recipes 2nd Edition

  • 8/16/2019 Curs EntityFramework

    3/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 3

    Entity Framework - EF

    Entity Framework este un set de tehnologii in ADO.NET ce suporta dezvoltarea de aplicatii

    software cu baze de date, aplicatii orientate pe obiecte. Comenzile din ADO.NET lucreaza cuscalari (date la nivel de coloana dintr-o tabela) in timp ce ADO.NET Entity Framework

    lucreaza cu obiecte (din baza de date se returneaza obiecte).

    Arhitectura ADO.NET Entity Framework consta din urmatoarele:

       Provideri specifici pentru sursa de date (Data source) ce abstractizeaza interfetele

    ADO.NET pentru conectare la baza de date cand programam folosind schema

    conceptula (model conceptual).

       Provider specific bazei de date ce translateaza comenzile Entity SQL in cereri native

    SQL (comenzi SQL din limbajul de definire a bazei de date, limbajul de cereri).

       Parser EDM (Entity Data Model) si mapare vizualizari prin tartarea specificatiilor

    SDL (Storage Data language –  model de memorare) al modelului de date, stabilireaasociatiilor dintre modelul relational (baza de date) si modelul conceptual. Din

    schema relationala se creaza vizualizari ale datelor ce corespund modelului

    conceptual. Informatii din mai multe tabele sunt agregate intr-o entitate. Actualizarea

     bazei de date (apel metoda SaveChanges()) are ca efect construirea comenzilor SQL

    specifice fiecarei tabele ce apare in acea entitate.

      Servicii pentru metadata ce gestioneaza metadata entitatilor, relatiilor si maparilor.

      Tranzactii  –  pentru a suporta posibilitatile tranzactionale ale bazei de date.

      Utilitare pentru proiectare  –  Mapping Designer –  incluse in mediul de dezvoltare.

       API pentru nivelul conceptual   –  runtime ce expune modelul de programare pentru a

    scrie cod folosind nivelul conceptual. Se folosesc obiecte de tip Connection,

    Command asemanator cu ADO.NET si se returneaza rezultate de tip EntityResultSets

    sau EntitySets.

      Componente deconectate  –  realizeaza un cache local pentru dataset si multimileentitati.

       Nivel de programare  –  ce expune EDM ca o constructie programabila si poate fi

    folosita in limbajele de programare ceea ce inseamna generare automata de cod  

     pentru clasele CLR ce expun aceleasi proprietati ca o entitate, permitand instantierea

    entitatilor ca obiecte .NET sau expun entitatile ca servicii web.

    Modele de programare

    1.  Aplicatie centrata pe baza de date  - Baza de date este in centrul aplicatiei.

    2.  Aplicatie centrata pe model   –  modelul este in centrul aplicatiei. Accesul la date este

    facut pe baza modelului conceptual, model ce reflecta obiectele problemei de

    rezolvat. In acest caz exista posibilitatea de a folosi : Code first   sau  Model design 

     first .

    1.  Modelul de programare centr at pe baza de date , presupune ca baza de date este creata

    si apoi se genereaza modelul logic ce contine tipurile folosite in logica aplicatiei.

    Acest lucru se face folosind mediul de dezvoltare VStudio. Se genereaza clasele

    POCO (EF versiune mai mare ca 4 si VS 2012/VS 2013) si fisierele necesare pentru

    nivelul conceptual, nivelul de mapare si nivelul de memorare.

  • 8/16/2019 Curs EntityFramework

    4/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 4

    2.  Aplicatia centrata pe model poate fi dezvoltata alegand una din variantele :

      Code first.

      Model design first.

    In cazulCode First 

    , dezvoltatorul scrie toate clasele (POCO) modelului si clasa derivatadin DbContext  cu toate entitatile necesare si apoi cu ajutorul mediului de dezvoltare se

    creaza si genereaza baza de date, tabelele din baza de date si informatiile aditionale necesare

     pentru EF.

    In cazul Model Design F ir st , mediul de dezvoltare permite dezvoltarea unei diagrame a

    modelului aplicatiei si pe baza acesteia se va crea si genera baza de date, tabelele din baza de

    date si informatiile aditionale necesare pentru EF.

    ADO.NET clasic presupune obiecte DataReader  / DataAdapter  pentru a citi

    informatii din baza de date si obiecte Command  pentru a executa insert, update, delete, etc.

    DataAdapter din ADO .NET este folosit pentru DataSet.

    In EF randurile si coloanele din tabele sunt returnate ca obiecte  si nu se foloseste in mod

    direct Command , se translateaza datele din forma tabelara in obiecte.

    Observatie Obiecte de tip Command pot fi folosite pentru accesul direct la baza de date sau pentru

    cazurile pe care EF nu le poate rezolva.

    EF foloseste un model numit  Entity Data Model   (EDM), dezvoltat din  Entity Relationship 

     Modeling  (ERM).

    Conceptele principale introduse de EDM sunt:

      Entity : entitatile sunt instante ale tipului Entity (de exemplu Customer , Order ).

    Acestea reprezinta structura unei inregistrari identificata printr-o cheie. Entitatile sunt

    grupate in multimi de Entity ( Entity-Sets).

      Relationship : relatiile asociaza entitatile si sunt instante ale tipurilor Relationship (de

    exemplu Order  postat de Customer ). Relatiile sunt grupate in multimi de relatii –  

     Relationship-Sets.

    EDM suporta diverse constructii ce extind aceste concepte de entitate si relatie:

      Inheritance : tipurile entitate pot fi definite astfel incat sa fie derivate din alte tipuri.

    Mostenirea in acest caz este una structurala, adica nu se mosteneste comportarea ci

    numai structura tipului entitate de baza.; in plus la aceasta mostenire a structurii, o

    instanta a tipului entitate derivat satisface relatia “is a”.

      Tipuri  complexe : EDM suporta definirea tipurilor complexe si folosirea acestora ca

    membri ai tipurilor entitate. De exemplu se poate defini tipul (clasa)  Address ce are

     proprietatile Street , City si Telephone si apoi sa folosim o proprietate de tip Address 

    in tipul entitate Customer .

    ERM defineste o schema a entitatilor si a relatiilor dintre acestea.

  • 8/16/2019 Curs EntityFramework

    5/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 5

    Entitatile definesc schema unui obiect, dar nu si comportarea acestuia. Entitatea este

    asemanatoare cu schema unei tabele din baza de date numai ca aceasta descrie schema

    obiectelor problemei de rezolvat - pe scurt modelul. 

    ERM apare pentru prima data in lucrarea lui Dr. Peter Chen: “The Entity-RelationshipModel — Toward a Unified View of Data” (http://csc.lsu.edu/news/erd.pdf )  –  1976.

    EDM este un model pe partea de client si constituie fundamentul pentru EF.

    EDM consta din trei niveluri, care sunt independente :

      nivelul conceptual (sau model conceptual) ;

      nivelul de mapare (sau model de mapare);

      nivelul de memorare (sau model de memorare).

    Clasele entitate sunt continute in modelul conceptual  din EDM.

    Nivelu l conceptual  poate fi modelat prin scriere directa de cod (model de programare code

     first ) –  modelul este in centrul aplicatiei –  sau folosind un utilitar pentru generarea entitatilor

    in situatia cand avem baza de date proiectata (model de programare database first ). Sintaxa

     pentru nivelul conceptual este definita de Conceptual Schema Definition Language (CSDL).

    Nivelu l de memorare  din EDM defineste tabele, coloane, relatii si tipuri de date ce sunt

    mapate la baza de date. Sintaxa pentru modelul de memorare este definita de Store Schema

     Definition Language (SSDL).

    Nivelu l de mapare  defineste maparea (legatura) dintre nivelul conceptual si nivelul de

    memorare. Printre altele, acest nivel defineste cum sunt mapate proprietatile din claseleentitate la coloanele tabelelor din baza de date.

     Mapping Specification Language (MSL) defineste sintaxa pentru nivelul de memorare.

    In EF, EDM este reprezentat in timpul proiectarii de un singur fisier XML din care la runtime

    se creeaza trei fisiere cu extensiile : csdl , msl, ssdl . Aceste fisiere contin descrierile pentru

    modelul conceptual, modelul de mapare si modelul de memorare.

    Terminologie

    http://csc.lsu.edu/news/erd.pdfhttp://csc.lsu.edu/news/erd.pdfhttp://csc.lsu.edu/news/erd.pdfhttp://csc.lsu.edu/news/erd.pdf

  • 8/16/2019 Curs EntityFramework

    6/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 6

    EntityType  reprezinta o clasa din model. O instanta a EntityType este referita ca o entitate.

    In mediul de dezvoltare, EntityType se reprezinta ca un dreptunghi cu diverse proprietati

    indicate in interior.

    EntityType  poate contine proprietati. Aceste proprietati se impart in :

    Proprietati de navigare  care se refera la alte entitati relationate –  in mod obisnuit

    reprezentate de relatiile furnizate de foreign key din bazele de date. Proprietatile de navigare

     pot fi de tip referinta sau de tip colectie.

    Proprietati scalare  : alte proprietati in afara celor de navigare –  proprietati automate in C# si

    reprezinta in fapt numele coloanelor dintr-o tabela si tipul de data asociat acestora.

    O relatie intre doua entitati se numeste asociere . Asocierea poate avea multiplicitate

    (cardinalitate) : 1-0..1, 1-n, n-n.

    EntityKey   –  identifica in mod unic entitatea in Entity Framework, si cel mai adesea este

    mapata la cheia primara corespunzatoare tabelei din baza de date. EntityKey este o proprietate

    in sens C#.

    Cele cinci entitati (exemplul de mai sus) formeaza impreuna un obiect graf . Un obiect graf

    este o vizualizare a unei entitati date, impreuna cu entitatile cu care relationeaza la un

    moment dat. De exemplu, la un moment dat, un Customer  cu Id = 10 poate avea numele

    “Alfa” , CustomerType. Name = “ Preferat ” si o colectie de 5 obiecte de tip CustomerEmail .

    Fiecarei clase de mai sus ii corespunde o tabela in baza de date. Numele tabelelor sunt:

    CustomerTypes, Customers, CustomerEmails, Products, ProductCategories si ProductCategoryProduct.

  • 8/16/2019 Curs EntityFramework

    7/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 7

    Observatie

    1.   Numele tabelelor corespunde cu numele entitatilor din clasa Model1Container .

    Descrierea acestei clase, derivata din DbContext, este data mai jos.

    2.  Relatia many-to-many are ca efect construirea unei tabele suplimentare, de legatura,intre tabelele implicate in aceasta relatie. In cazul de fata tabela suplimentara este

     ProductCategoryProduct  care are definite doua chei straine ce puncteaza la cheile

     primare din tabelele implicate in relatie.

    Tabela de legatura ProductCategoryProduct , intre tabelele ProductCategories si Products 

    este definita (de catre mediul de dezvoltare) astfel :

    CREATE TABLE [dbo].[ProductCategoryProduct] ( 

    [ProductCategories_ProductCategoryId] INT NOT NULL, [Products_ProductId] INT NOT NULL, 

    CONSTRAINT [PK_ProductCategoryProduct] PRIMARY KEY CLUSTERED([ProductCategories_ProductCategoryId] ASC, [Products_ProductId] ASC), 

    CONSTRAINT [FK_ProductCategoryProduct_ProductCategory] FOREIGN KEY

    ([ProductCategories_ProductCategoryId]) REFERENCES [dbo].[ProductCategories] ([ProductCategoryId]), 

    CONSTRAINT [FK_ProductCategoryProduct_Product] FOREIGN KEY ([Products_ProductId]) REFERENCES [dbo].[Products] ([ProductId]) );

    Tabela are o cheie primara definita de coloanele ProductCategories_ProductCategoryId si

    Products_ProductId, si doua foreign keys.

    Pentru diagrama de mai sus clasele generate sunt (dau numai primele doua clase):

    public partial class CustomerType {

    public CustomerType(){

    this.Customers = new HashSet();

    }

    public int CustomerTypeId { get; set; }public string Description { get; set; }

    public virtual ICollection Customers { get; set; }

    }

    public partial class Customer 

  • 8/16/2019 Curs EntityFramework

    8/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 8

    {public Customer()

    {this.CustomerEmails = new HashSet();

    }

    public int CustomerId { get; set; }public string Name { get; set; }public string CustomerTypeId { get; set; }

    public int CustomerTypeCustomerTypeId { get; set; }

    public virtual CustomerType CustomerType { get; set; }public virtual ICollection CustomerEmails { get; set; }

    }

    Contextul este definit dupa cum urmeaza:

    public partial class Model1Container : DbContext 

    {public Model1Container()

    : base("name=Model1Container") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder){

    throw new UnintentionalCodeFirstException();}

    public virtual DbSet Customers { get; set; }public virtual DbSet CustomerTypes { get; set; }

    public virtual DbSet CustomerEmails { get; set; }public virtual DbSet ProductCategories { get; set; }

    public virtual DbSet Products { get; set; }} 

    Observati cum sunt modelate relatiile 1->* (one-to-many) in C# prin definirea proprietatilor

    de navigare de tip referinta si/sau de tip colectie.Un obiect CustomerType poate avea asociat

    mai multe obiecte de tip Customer , deci in clasa CustomerType se defineste proprietatea de

    navigare de tip colectie:

    public virtual ICollection Customers { get; set; }

    Un obiect de tip Customer  face referire la un singur CustomerType, si ca atare in clasa

    Customer  se defineste proprietatea de navigare de tip refererinta :

    public virtual CustomerType CustomerType { get; set; }

    In acest mod se implementeaza in EF relatiile definite de chei primare si chei straine.

    In cazul relatiilor *->* (many-to-many) in fiecare clasa se defineste o proprietate de navigare

    de tip colectie. Aceste colectii contin instante ale tipului cu care intra in relatie tipul dat.

    Contextul in Entity Framework

    Pana la versiunea 4 (Visual Studio 2008), contextul in EF era definit numai de clasele

    ObjectContext si ObjectSet. Incepand cu versiunea 4.1 s-au creat clasele DbContext siDbSet, clase ce sunt wrapper-e pentru ObjectContext si ObjectSet. Pentru a intelege

  • 8/16/2019 Curs EntityFramework

    9/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 9

    mai bine calsele DbContext si DbSet vom studia mai intai clasele ObjectContext si

    ObjectSet. Nu vom prezenta exemple cu EF versiunea 4.

    Clasa ObjectContext  

    Context object  (clasa ContextObject )  reprezinta accesul la serviciile din EF.

    ContextObject  

      expune obiecte entitate;

      gestioneaza conexiunile la baza de date;

      genereaza SQL parametrizat;

      transfera date din / in baza de date;

      realizeaza cache la obiecte;

     jurnalizeaza modificarile efectuate;

      materializeaza sau transforma o multime rezultat fara tip intr-o colectie de obiecte

     puternic tipizate.

    ObjectContext interactioneaza cu clasele ObjectSet, ObjectQuery.

    Observatie DbContext interactioneaza cu clasele DbSet, DbQuery.

    Clasa ObjectContext permite interactiunea cu date ca obiecte ce sunt instante ale tipurilor

    entitati, definite in modelul conceptual.

    O instanta a tipului ObjectContext contine informatii despre:

      conexiune la baza de date, in forma unui obiect EntityConnection.

      Metadata ce descrie modelul, in forma unui obiect MetadataWorkspace.

      Un obiect ObjectStateManager ce gestioneaza obiectele memorate in cache.

    Clasa ce reprezinta EntityContainer pentru model, este derivata din ObjectContext.

    Metode (MSDN) uzuale pentru ObjectContext.

     Name Description

     AcceptAllChanges Accepts all changes made to objects in the object context.

     AddObject Adds an object to the object context.

    CreateDatabaseCreates the database by using the current data source

    connection and the metadata in the StoreItemCollection. 

    DeleteDatabaseDeletes the database that is specified as the database in the

    current data source connection.

    DeleteObject Marks an object for deletion.

    DetectChangesEnsures that ObjectStateEntry changes are synchronized

    with changes in all objects that are tracked by the

    ObjectStateManager . 

    ExecuteStoreCommand   Executes an arbitrary command directly against the data

    http://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.acceptallchanges&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.addobject(system.string%2csystem.object)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.createdatabase&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.metadata.edm.storeitemcollection&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.metadata.edm.storeitemcollection&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.metadata.edm.storeitemcollection&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.deletedatabase&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.deleteobject(system.object)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.detectchanges&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstateentry&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstateentry&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstateentry&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstatemanager&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstatemanager&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.executestorecommand(system.string%2csystem.object%5b%5d)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.executestorecommand(system.string%2csystem.object%5b%5d)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.executestorecommand(system.string%2csystem.object%5b%5d)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstatemanager&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstateentry&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.detectchanges&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.deleteobject(system.object)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.deletedatabase&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.metadata.edm.storeitemcollection&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.createdatabase&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.addobject(system.string%2csystem.object)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.acceptallchanges&vendor=Microsoft&topicVersion=100&topicLocale=EN-US

  • 8/16/2019 Curs EntityFramework

    10/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 10

    source using the existing connection.

    SaveChanges()Persists all updates to the data source and resets change

    tracking in the object context.

    SaveChanges(SaveOptions) 

    Persists all updates to the data source with the specified

    SaveOptions. 

     Attach 

    Attaches an object or object graph to the object context

    when the object has an entity key.

     AttachTo 

    Attaches an object or object graph to the object context in a

    specific entity set.

    Clasa ObjectSet

    Un obiect din ObjectSet reprezinta o multime entitate tipizata folosita pentru operatii de

    creare, modificare, citire si stergere din baza de date.

     Exemplu de declarare (EF versiunea 4).

    Proprietatea Customers va returna multimea inregistrarilor din tabela “Customer ” din baza

    de date (asa a fost definit modelul), folosind conexiunea data de un obiect de tip

    CustomerOrderEntities.

     public  partial class CustomerOrderEntities : ObjectContext {

    // cod lipsa

     public ObjectSet  Customers{

    get {

    if ((_Customers == null)){ _Customers = base.CreateObjectSet("Customers");

    }return _Customers;

    }} private ObjectSet  _Customers;

    }

    Clasa Customer  va contine numai proprietati. Aceste proprietati corespund coloanelor tabelei

    Customer existenta in baza de date. Observati modul de dfinire al proprietatii Customers.

    Metode importante pentru ObjectSet (MSDN)

     Name Description

     AddObject Adds an object to the object context in the current entity set.

     ApplyCurrentValues Copies the scalar values from the supplied object into the object inthe ObjectContext that has the same key.

    http://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.savechanges&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.savechanges(system.data.objects.saveoptions)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.savechanges(system.data.objects.saveoptions)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.saveoptions&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.attach(system.data.objects.dataclasses.ientitywithkey)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.attachto(system.string%2csystem.object)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.addobject(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.applycurrentvalues(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectcontext&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectcontext&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectcontext&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectcontext&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.applycurrentvalues(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.addobject(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.attachto(system.string%2csystem.object)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.attach(system.data.objects.dataclasses.ientitywithkey)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.saveoptions&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.savechanges(system.data.objects.saveoptions)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectcontext.savechanges&vendor=Microsoft&topicVersion=100&topicLocale=EN-US

  • 8/16/2019 Curs EntityFramework

    11/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 11

     ApplyOriginalValues Sets the OriginalValues  property of an ObjectStateEntry to match

    the property values of a supplied object.

     AttachAttaches an object or object graph to the object context in the

    current entity set.

    DeleteObject Marks an object for deletion.

    Detach Removes the object from the object context.

    ExecuteExecutes the object query with the specified merge option.

    (Inherited from ObjectQuery(T).)

    IncludeSpecifies the related objects to include in the query results.

    (Inherited from ObjectQuery(T) .)

    Etapele necesare pentru adaugare, regasire si stergere informatii din baza de date sunt definite

    in continuare.

     Adaugare

    Pentru a  adauga o inregistrare in tabela Customer  (in cazul nostru) procedam in modul

    urmator :

    1.  Cream o instanta a tipului Customer . Completam proprietatile corespunzatoare.2. Customer customer = new Customer(...) ;

    3.  Adaugam obiectul la colectie. Vom folosi metoda :

    4.  AddObject() din ObjectSet sau AddObjectTo definita in clasa Customer .

    5.  Salavare in baza de date : folosim metoda SaveChanges() pe un obiect de tip

    ObjectContext.

    ModificarePentru a modifica o inregistrare trebuie sa efectuam urmatorii pasi :

    1.  Conexiune la baza de date –  creare instanta tip derivat din ObjectContext.2.  Determinare in cadrul colectiei a obiectului (lor) ce trebuie(sc) modificat(e). Metode

    de tip select, Find din LINQ, etc.

    3.  Modificare obiect.

    4.  Salvare in baza de date : folosim metoda SaveChanges() pe un obiect de tip

    ObjectContext.

    StergerePentru a sterge o inregistrare trebuie sa efectuam urmatorii pasi :

    1.  Conexiune la baza de date –  creare instanta tip derivat din ObjectContext.

    2.  Determinare in cadrul colectiei a obiectului (lor) ce trebuie(sc) sters(e). Metode de tip

    select, Find din LINQ, etc.

    3.  Apel metoda DeleteObject, ce are ca efect marcarea obiectului pentru stergere.

    4.  Stergere efectiva - salvare in baza de date : folosim metoda SaveChanges() pe un

    obiect de tip ObjectContext.

    Metodele din ObjectSet lucreaza pe colectii de obiecte.

    http://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.applyoriginalvalues(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.applyoriginalvalues(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.objects.objectstateentry.originalvalues&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.objects.objectstateentry.originalvalues&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.objects.objectstateentry.originalvalues&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstateentry&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstateentry&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstateentry&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.attach(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.deleteobject(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.detach(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectquery%601.execute(system.data.objects.mergeoption)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectquery%601.include(system.string)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectquery%601&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectquery%601&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectquery%601&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectquery%601&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectquery%601.include(system.string)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectquery%601.execute(system.data.objects.mergeoption)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.detach(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.deleteobject(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.attach(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.objects.objectstateentry&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.objects.objectstateentry.originalvalues&vendor=Microsoft&topicVersion=100&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.objects.objectset%601.applyoriginalvalues(%600)&vendor=Microsoft&topicVersion=100&topicLocale=EN-US

  • 8/16/2019 Curs EntityFramework

    12/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 12

    Metodele ExecuteStoreQuery si ExecuteStoreCommand – acces direct la

    baza de date

    Metodele ExecuteStoreQuery si ExecuteStoreCommand  din ObjectContext permit

    executia de comenzi SQL direct la nivel de baza de date, fara a folosi modelul conceptualgenerat. Din EDM se foloseste doar conexiunea.

    Exista doua prototipuri pentru ExecuteStoreQuery  (MSDN).

     public ObjectResult ExecuteStoreQuery(

    string commandText,

     params Object[] parameters

    )

    Type Parameters

    TElement  Parameters

    commandText  Type: System.String 

    The command to execute, in the native language of the data source.

     parameters Type: System.Object[]

    An array of parameters to pass to the command.

    Return Value

    Type: System.Data.Objects.ObjectResult

    An enumeration of objects of type TResult .

    Metoda ExecuteStoreQuery foloseste conexiunea existenta pentru a executa o comanda in

    mod direct asupra sursei de date. Se foloseste tranzactia existenta, daca o asemnea tranzactie

    exista.

    ExecuteStoreQuery echivalentul metodei ExecuteReader din clasa DbCommand  cu

    observatia ca ExecuteStoreQuery returneaza entitati si nu valori scalare precum

    ExecuteReader.

    Putem apela metoda Translate pentru a transforma un DbDataReader in obiecte entitate

    in situatia cand reader-ul contine inregistrari ce sunt mapate la un tip entitate specificat.

    Valoarea pentru parameters poate fi un array de DbParameter sau un array de valori pentru

     parametru.

    Al doilea prototip pentru ExecuteStoreQuery este:

     public ObjectResult ExecuteStoreQuery(

    string commandText,

    string entitySetName,

     MergeOption mergeOption, params Object[] parameters

    http://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/bb739113(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/bb739113(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/bb739113(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx

  • 8/16/2019 Curs EntityFramework

    13/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 13

    )

    Type Parameters

    TEntity  

    ParameterscommandText  

    Type: System.String The command to execute, in the native language of the data source.

    entitySetName Type: System.String 

    The entity set of the TResult  type. If an entity set name is not provided, the results are not going to be

    tracked.

    mergeOption 

    Type: System.Data.Objects.MergeOption The MergeOption to use when executing the query. The default is AppendOnly. 

     parameters Type: System.Object[]An array of parameters to pass to the command.

    Return Value

    Type: System.Data.Objects.ObjectResultAn enumeration of objects of type TResult .

    Exemple  (MSDN)

    Pasare parametri la o comanda SQLTrei modalitati diferite pentru a pasa parametri la o comanda SQL.

    Cererile returneaza un tip string.

    using (SchoolEntities context = new SchoolEntities())

    {

    // 1. Pattern substitutie parametru.

    // Returneaza string. 

    foreach (string name in context.ExecuteStoreQuery

    ("Select Name from Department where DepartmentID < {0}", 5))

    {

    Console.WriteLine(name);

    }

    // 2. Utilizare folosind sintaxa parametrizata. Asemanator cu 1. 

    foreach (string name in context.ExecuteStoreQuery

    ("Select Name from Department where DepartmentID < @p0", 5))

    {

    Console.WriteLine(name);

    }// 3. Utilizare explicita SqlParameter. 

    http://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/bb739113(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/bb739113(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/bb739113(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx

  • 8/16/2019 Curs EntityFramework

    14/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 14

    foreach (string name in context.ExecuteStoreQuery

    ("Select Name from Department where DepartmentID < @p0",

    new SqlParameter { ParameterName = "p0", Value = 5 }))

    {

    Console.WriteLine(name);

    }

    }

    Exemplu (MSDN) : Metodele ExecuteStoreCommand si ExecuteStoreQuery

    Se citesc inregistrari din tabela Department  si se genereaza obiecte de tip DepartmenInfo.

    Vedeti metoda ExecuteStoreQuery prezentata mai jos.

    Se creaza o clasa DepartmentInfo ce are numele proprietatilor aceleasi cu numele coloanelor

    din tabela Department . Se vor insera inregistrari in tabela Department , se va obtine un obiect DepartmentInfo executand o cerere asupra tabelei Department  si in final se va sterge

    inregistrarea adaugata.

     public class DepartmentInfo

    {

     private DateTime _startDate;

     private String _name;

     private Int32 _departmentID;

    // Se definesc proprietatile pentru cele trei date membru private

     public Int32 DepartmentID

    {

    get { return _departmentID; }

    set { _departmentID = value;}

    }

     public String Name

    {

    get { return _name; }

    set { _name = value;}

    } public DateTime StartDate

    {

    get { return _startDate; }

    set { _startDate = value;}

    }

    }

     public static void  ExecuteStoreCommands()

    {// Executie comenzi SQL direct asupra bazei de date. Din EF// se foloseste numai conexiunea

  • 8/16/2019 Curs EntityFramework

    15/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 15

    using (SchoolEntities context = new SchoolEntities())

    {

    int DepartmentID = 21;// Insert inregistrare in tabela Department.

    // Se foloseste substitutia parametrilor. int rowsAffected = context.ExecuteStoreCommand(

    "Insert Department values ({0}, {1}, {2}, {3}, {4})",

    DepartmentID, "Engineering", 350000.00, "2009-09-01", 2);

    Console.WriteLine("Number of affected rows: {0}", rowsAffected);

    // Obtinem obiectul DepartmentInfo.

    DepartmentInfo department =

    context.ExecuteStoreQuery

    ("Select * from Department where DepartmentID= {0}",

    DepartmentID).FirstOrDefault();

    Console.WriteLine("ID: {0}, Name: {1} ", department.DepartmentID,

    department.Name);

    // Stergere inregistrare din Departament

    rowsAffected = context.ExecuteStoreCommand(

    "Delete from Department where DepartmentID = {0}", DepartmentID);

    Console.WriteLine("Number of affected rows: {0}", rowsAffected);

    }}

    Exemplu (MSDN) : In actiune metoda Translate.

    Se creaza un DataReader si apoi tipurile scalare din DataReader sunt transformate in

    obiecte de tip Department . In prima etapa se foloseste pentru conexiune clasa

    SqlConnection, iar in a doua etapa se foloseste conexiunea data de EF.

    Se returneaza un DbDataReader si apoi se translateaza DbDataReader in obiecte ale

    tipului Department .

    // Initializare string conexiuneSqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();

    sqlBuilder.DataSource = ".";

    sqlBuilder.InitialCatalog = "School";

    sqlBuilder.IntegratedSecurity = true;

    // Conectare la baza de date folosind SqlConnection

    SqlConnection con = new  SqlConnection(sqlBuilder.ToString());

    {

    con.Open();

    DbCommand cmd = con.CreateCommand();

  • 8/16/2019 Curs EntityFramework

    16/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 16

    cmd.CommandText = @"SELECT * FROM Department";

    // Creare reader ce contine inregistrari din Department.

    using (DbDataReader rdr =

    cmd.ExecuteReader(CommandBehavior.SequentialAccess))

    {

    // Conectare la baza de date folosind contextul din EF

    using (SchoolEntities context = new SchoolEntities())

    {

    // Translateza reader-ul la obiecte de tipul Department. 

    foreach (Department d in  context.Translate(rdr))

    {

    Console.WriteLine("DepartmentID: {0} ", d.DepartmentID);

    }}

    }

    con.Close();

    }

    Exemplu (MSDN): ObjectQuery  

    using (AdventureWorksEntities context = new AdventureWorksEntities())

    {

    // Se returneaza un obiect

    string esqlQuery = @"SELECT VALUE Contact

    FROM AdventureWorksEntities.Contacts as Contact where

    Contact.LastName = @ln";

    // Urmatoarea cerere returneaza o colectie de obiecte Contact.

    ObjectQuery query = new  ObjectQuery(esqlQuery,

    context, MergeOption.NoTracking);

    query.Parameters.Add(new ObjectParameter("ln", "Zhou"));

    // Iterare colectie. 

    foreach (Contact result in query)

    Console.WriteLine("Contact First Name: {0}; Last Name: {1}",

    result.FirstName, result.LastName);

    }

    sau folosing Linq

    using (AdventureWorksEntities context = new AdventureWorksEntities())

    {

  • 8/16/2019 Curs EntityFramework

    17/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 17

    ObjectQuery query= context.Contacts.Where("it.LastName==@ln",

    new ObjectParameter("ln", "Zhou"));

    // Iterare colectie.

    foreach (Contact result in query)

    Console.WriteLine("Contact First Name: {0}; Last Name: {1}",

    result.FirstName, result.LastName);}

    Clasa DbContext

    Conceptual aceasta clasa este similara cu ObjectContext. Se foloseste pentru a executa

    cereri asupra EDM si a efectua actualizarea bazei de date (insert, update, delete, cereri).

    Aceasta clasa este folosita in versiunile EF mai mari sau egale cu 4.1.

    Exemplu de clasa derivata din DbContext : public class ProductContext : DbContext

    { public DbSet Categories { get; set; }

     public DbSet Products { get; set; }}

    Observatie Daca folosim modelul de programare Code First , atunci aceasta clasa trebuie sa o scriem noi.

    Daca folosim modelul de programare Databse first , atunci aceasta clasa este generata de un

    utilitar apelat de catre mediul de dezvoltare Visual Studio.

    Odata ce avem un context, putem adauga (vezi metodele Add  si Attach) sau sterge (vezi

    metoda Remove) entitati din acest context folosind proprietatile definite in cadrul lui (in

    exemplu Categories si Products). Accesarea unei proprietati DbSet din cadrul

    contextului reprezinta startul unei cereri ce returneaza toate entitatile de tipul specificat.

    Faptul ca accesam o proprietate nu inseamna ca cererea se executa. O cerere este executata

    cand:

      Este enumerata in foreach.

      Este enumerata de o operatiune din colectie cum ar fi ToArray, ToDictionary sau

    ToList .  Sunt specificati in cadrul cererii operatorii LINQ First  sau Any .

      Sunt apelate urmatoarele metode: metoda extinsa Load  pe un DbSet,

     DbEntityEntry.Reload  si Database.ExecuteSqlCommand .

    Timpul de viata al contextului – recomandari

    Un context este valabil din momentul in care s-a creat o instanta a acestuia si este disponibil

     pana cand se apeleaza metoda Dispose sau este luata in considerare de catre garbage

    collector. Se recomanda folosirea lui using.

  • 8/16/2019 Curs EntityFramework

    18/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 18

    using (var context = new ProductContext())

    {// Acces la date folosind contextul 

    }

    Recomandarile Microsoft pentru lucrul cu contextul in EF sunt urmatoarele:

      Performanta aplicatiei poate scadea in cazul cand incarcam in memorie multe obiecte

    din cadrul aceluiasi context. Consum sporit de memorie plus accesarea obiectelor are

    nevoie de mai mult timp procesor.

      Daca o exceptie are ca efect trecerea contextului intr-o stare pe care sistemul nu o

     poate gestiona este posibil ca aplicatia sa se termine.

      Daca timpul dintre incarcarea datelor unei cereri si actualizarea acestora este mare, e posibil sa apara probleme legate de concurenta.

      In aplicatiile Web, trebuie sa folosim instanta unui context pe fiecare cerere.

      In aplicatiile WPF sau Windows Forms se recomanda utilizarea unei instante a

    contextului la nivel de fereastra (formular).

    DbContext se foloseste de regula cu un tip derivat ce contine proprietati DbSet 

     pentru entitatile modelului. Aceste multimi sunt initializate in mod automat cand se creaza o

    instanta a clasei derivate. Aceasta comportare poate fi suprimata daca aplicam atributul

    SuppressDbSetInitializationAttribute, fie la intreaga clasa context, fie la

     proprietati individuale din cadrul clasei.

    Proprietati pentru DbContext :

    ChangeTrackerProvides access to features of the context that deal with change tracking

    of entities.

    Configuration 

    Provides access to configuration options for the context.

    Database Creates a Database instance for this context that allows forcreation/deletion/existence checks for the underlying database.

    Metode pentru DbContext (MSDN)

     Name Description

    Entry(Object) 

    sau forma generica

    Entry(TEntity) 

    Gets a DbEntityEntry object for the given entity providing access to

    information about the entity and the ability to perform actions on the

    entity.

    http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.suppressdbsetinitializationattribute(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.changetracker(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.configuration(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.database(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696238(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696578(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696578(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696578(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696578(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696238(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.database(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.configuration(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.changetracker(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.changetracker(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.suppressdbsetinitializationattribute(v=vs.113).aspx

  • 8/16/2019 Curs EntityFramework

    19/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 19

    OnModelCreating() This method is called when the model for a derived context has beeninitialized, but before the model has been locked down and used to

    initialize the context. The default implementation of this method

    does nothing, but it can be overridden in a derived class such that the

    model can be further configured before it is locked down.

    SaveChanges() Saves all changes made in this context to the underlying database.

    SaveChangesAsync() SaveChangesAsync(CancellationToken) 

    Asynchronously saves all changes made in this context to the

    underlying database.

    Set(Type) Returns a non-generic DbSet instance for access to entities of thegiven type in the context, the ObjectStateManager, and the

    underlying store.

    Set() Returns a DbSet instance for access to entities of the given type inthe context, the ObjectStateManager, and the underlying store.

    Executie comenzi SQL la nivel de baza de date – proprietatea Database

    Prin proprietatea Database obtinem un obiect Database. Acest obiect expune metode ce pot

    executa comenzi SQL (DDL/DML) la nivel de baza de date.

    Clasa Database expune proprietatea Connection ce permite recrearea unui obiect

    DbConnection daca acesta nu exista.

    Metode importante din clasa - Database:

     Name Description

    BeginTransaction()  Begins a transaction on the underlying store connection.

    BeginTransaction(

    IsolationLevel)

    Begins a transaction on the underlying store connection

    using the specified isolation level.

    Create Creates a new database on the database server for the

    model defined in the backing context. Note that calling

    this method before the database initialization strategy has

    run will disable executing that strategy.

    CreateIfNotExists Creates a new database on the database server for the

    model defined in the backing context, but only if a

    database with the same name does not already exist onthe server.

    http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.onmodelcreating(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.savechanges(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220070(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220059(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220059(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679544(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696521(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220052(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220052(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220039(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220039(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.database.create(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.database.createifnotexists(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.database.createifnotexists(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.database.create(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220039(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220039(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220052(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696521(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679544(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220059(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220059(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220070(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.savechanges(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.onmodelcreating(v=vs.113).aspx

  • 8/16/2019 Curs EntityFramework

    20/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 20

    Delete() Deletes the database on the database server if it exists,

    otherwise does nothing. Calling this method from outside

    of an initializer will mark the database as having not been

    initialized. This means that if an attempt is made to use

    the database again after it has been deleted, then any

    initializer set will run again and, usually, will try to create

    the database again automatically.

    ExecuteSqlCommand

    (String, Object[]) 

    Executes the given DDL/DML command against the

    database.

    ExecuteSqlCommandA 

    sync(String,

    CancellationToken, Object[])

    Asynchronously executes the given DDL/DML command

    against the database.

    SqlQuery(Type,

    String, Object[]) 

    Cazul generic

    SqlQuery 

    (String, Object[]) 

    Creates a raw SQL query that will return elements of the

    given (generic) type. The type can be any type that has

     properties that match the names of the columns returned

    from the query, or can be a simple primitive type. The

    type does not have to be an entity type. The results of this

    query are never tracked by the context even if the type of

    object returned is an entity type. Use

    the SqlQuery(String, Object[]) method to return entitiesthat are tracked by the context.

    Exemplu. Cereri cu SqlQuery pentru entitati

    Cereri SQL pentru entitati  –  Blogs este o entitate :

    using (var context = new BloggingContext())

    {

    var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();

    }

    Cereri SqlQuery pentru tipuri non-entitate   –  acces direct la tabela Blogs :

    using (var context = new BloggingContext())

    {

    var blogNames = context.Database.SqlQuery(

    "SELECT Name FROM dbo.Blogs").ToList();

    }

    http://msdn.microsoft.com/en-us/library/gg696770(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679456(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679456(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679456(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220056(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220056(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220056(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220056(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679117(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679117(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696545(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696545(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbset.sqlquery(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbset.sqlquery(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbset.sqlquery(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbset.sqlquery(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696545(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696545(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679117(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679117(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220056(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220056(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220056(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220056(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679456(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679456(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696770(v=vs.113).aspx

  • 8/16/2019 Curs EntityFramework

    21/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 21

    Clasa DbSet 

    Aceasta clasa este folosita cand tipul entitatii nu este cunoscut in momentul constructiei. Este

    versiunea non-generica pentru DbSet.

    Metode pentru DbSet (MSDN)

     Name Description

     Add   AddRange 

    Adds the given entity to the context underlying the set in the Added

    state such that it will be inserted into the database when SaveChanges is

    called.

     Attach Attaches the given entity to the context underlying the set. That is, the

    entity is placed into the context in the Unchanged state, just as if it had been read from the database.

    Create() Create() 

    Creates a new instance of an entity for the type of this set. Note that this

    instance is NOT added or attached to the set. The instance returned will

     be a proxy if the underlying context is configured to create proxies and

    the entity type meets the requirements for creating a proxy.

    Find  Finds an entity with the given primary key values. If an entity with thegiven primary key values exists in the context, then it is returned

    immediately without making a request to the store. Otherwise, a requestis made to the store for an entity with the given primary key values and

    this entity, if found, is attached to the context and returned. If no entity

    is found in the context or the store, then null is returned.

    Include Specifies the related objects to include in the query results. (Inheritedfrom DbQuery.)

    Remove RemoveRange 

    Marks the given entity as Deleted such that it will be deleted from the

    database when SaveChanges is called. Note that the entity must exist in

    the context in some other state before this method is called.

    SqlQuery Creates a raw SQL query that will return entities in this set. By default,the entities returned are tracked by the context; this can be changed by

    calling AsNoTracking on the DbSqlQuery returned. Note

    that the entities returned are always of the type for this set and never of

    a derived type. If the table or tables queried may contain data for other

    entity types, then the SQL query must be written appropriately to

    ensure that only entities of the correct type are returned.

    http://msdn.microsoft.com/en-us/library/gg679587(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220168(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696261(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696136(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696685(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696685(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696418(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696785(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696530(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696530(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696530(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679171(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220170(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696332(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679457(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679457(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679457(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679457(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696332(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220170(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679171(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696530(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696785(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696418(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696685(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696685(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696136(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg696261(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/dn220168(v=vs.113).aspxhttp://msdn.microsoft.com/en-us/library/gg679587(v=vs.113).aspx

  • 8/16/2019 Curs EntityFramework

    22/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 22

    Reprezentari ale modelului conceptual

    Un model conceptual este o reprezentare specifica a structurii unor date vazute ca entitati si

    relatii.

    In VS avem o reprezentare vizuala a EDM-ului si a membrilor sai. In spatele acestei

    reprezentari vizuale exista un fisier XML.

    Metadata modelului (vezi cele trei fisiere)

      Baza de date

      Maparea

    Alte denumiri utile

    Conceptual Schema Definition Language (CSDL)

      • Conceptual layer  

      • Conceptual schema

      • Conceptual model 

      • C-side

    Store Schema Definition Language (SSDL)

      • Store/storage layer  

     • Store/storage schema   • Store/storage model 

    http://void%280%29/http://void%280%29/

  • 8/16/2019 Curs EntityFramework

    23/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 23

      • Store/storage metadata 

      • Store/storage metadata schema 

      • S-side

    Mapping Specification Language (MSL)

      • Mapping layer  • Mapping specification 

      • C-S mapping (referring to “conceptual to store”) 

    Ce exista in fisierul XML ce descrie EDM?

    Doua sectiuni principale :

      informatii pentru runtime ;

    o  modelul de memorare ;

    o  modelul conceptual ;

    o  maparea ;

      informatii pentru Designer.

    CSDL: Schema conceptuala

    EntityContainerEntitySetEntityType

    EntityContainer

    Constituie punctul principal pentru a executa cereri asupra modelului.

    Un EntityContainer este o grupare logica de multimi de entitati si multimi de asociatii.

    La nivel conceptual, clasa EntityContainer reprezinta un container ce va fi mapat la un

    obiect baza de date in modelul de memorare. In modelul de memorare, clasa

    EntityContainer reprezinta o descriere a tabelei si/sau relatiilor.

    EntityContainer expune EntitySets care dau acces la obiectele pe care le contin.

  • 8/16/2019 Curs EntityFramework

    24/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 24

    Proprietatea LazyLoadingEnabled  determina modul cum sunt incarcate in memorie datele

    cu care relationeaza un anumit obiect. 

    EntitySet

    Un EntitySet este un container de tip entitate si are atributele Name si EntityType.

      

    EntityType

    EntityType este tipul de data din model.

      

         ... 

     

  • 8/16/2019 Curs EntityFramework

    25/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 25

    .NET Framework Data Provider pentru Entity Framework.

    Spatiul de nume EntityClient.

    Provider-ul EntityClient foloseste clase specifice ADO.NET Data Provider si mapeazametadata pentru interactiune cu modelele de date entitate. EntityClient translateaza operatiile

    efectuate pe entitatile conceptuale in operatii efectuate pe sursa de date fizica, translateaza

    multimile rezultat returnate din sursa fizica de date in entitati conceptuale.

    Clasele din acest namespace sunt:

    Class Description

    EntityCommand  Represents a command for the conceptual layer.

    EntityConnection Contains a reference to a conceptual model and a datasource connection. This class cannot be inherited.

    EntityConnectionStringBuilder

    Provides a simple way to create and manage the

    contents of connection strings used by the

    EntityClient.

    EntityDataReader Reads a forward-only stream of rows from a datasource.

    EntityParameter Represents a parameter used in EntityCommand.

    EntityParameterCollection

    Represents a collection of parameters associated with

    a EntityCommand. 

    EntityProviderFactory  Represents a set of methods for creating instances of a provider's implementation of the data source classes.

    EntityTransaction  Specifies the transaction for an EntityCommand.

    Observatie Aceste clase se aseamana cu cele din ADO.NET situate in nivelul cu conexiune  –  mai putin

    DataAdapter care nu are corespondent aici pentru ca nu exista DataSet in EF.

    In continuare va fi descrisa fiecare clasa.

    Clasa EntityConnection

    Namespace:  System.Data.EntityClient Assembly:System.Data.Entity (in System.Data.Entity.dll) 

    http://msdn.microsoft.com/en-us/library/system.data.entityclient.entitycommand(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnection(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnectionstringbuilder(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnectionstringbuilder(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitydatareader(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityparameter(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityparametercollection(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityparametercollection(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitycommand(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitycommand(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitycommand(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityproviderfactory(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityproviderfactory(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitytransaction(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitytransaction(v=vs.110).aspxhttp://ms-xhelp//?method=page&id=n%3asystem.data.entityclient&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=n%3asystem.data.entityclient&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=n%3asystem.data.entityclient&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitytransaction(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityproviderfactory(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitycommand(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityparametercollection(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityparametercollection(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityparameter(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitydatareader(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnectionstringbuilder(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnectionstringbuilder(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnection(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entitycommand(v=vs.110).aspx

  • 8/16/2019 Curs EntityFramework

    26/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 26

    Contine o referinta la modelul conceptual si stabileste o conexiune la sursa de date.

    Mod de lucru asemanator cu Connection din ADO.NET.

    Cand construim un obiect EntityConnection trebuie sa furnizam stringul de conexiune.

    Acest lucru poate fi facut in urmatoarele moduri:

      furnizam un string de conexiune complet;

      furnizam un string formatat ce contine cuvantul cheie Name astfel (bazat pe exemplul

    din curs):

     Name=Model1Container

    unde Model1Container  este numele stringului de conexiune din fisierul de configurare.

    Proprietatea StoreConnection, de tip DbConnection, din EntityConnection  reprezinta oconexiune fizica la baza de date.

    Proprietati EntityConnection

     Name Description

    ConnectionString Gets or sets the EntityConnection connection string.

    ConnectionTimeoutGets the number of seconds to wait when attempting to establish a

    connection before ending the attempt and generating an error.

    Container Gets the IContainer  that contains the Component. 

    Database Gets the name of the current database, or the database that will beused after a connection is opened.

    DataSource Gets the name or network address of the data source to connect to.

    ServerVersionGets a string that contains the version of the data source to which the

    client is connected.

    StateGets the ConnectionState  property of the underlying provider if the

    EntityConnection is open. Otherwise, returns Closed. 

    StoreConnectionProvides access to the underlying data source connection that is used

     by the EntityConnection object.

    Metode EntityConnection

     Name Description

    BeginTransaction()Begins a transaction by using the underlying

     provider.

    BeginTransaction(IsolationLevel) Begins a transaction with the specified isolation

    level by using the underlying provider.

    Close Closes the connection to the database.

    CreateCommand  Creates a new instance of an EntityCommand, 

    http://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.connectionstring&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.connectiontimeout&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.componentmodel.component.container&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.componentmodel.icontainer&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.componentmodel.icontainer&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.componentmodel.icontainer&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.componentmodel.component&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.componentmodel.component&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.componentmodel.component&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.database&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.datasource&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.serverversion&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.state&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.connectionstate&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.connectionstate&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.connectionstate&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.connectionstate&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.connectionstate&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.connectionstate&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.storeconnection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.begintransaction&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.begintransaction(system.data.isolationlevel)&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.begintransaction(system.data.isolationlevel)&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.close&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.createcommand&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.entityclient.entitycommand&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.entityclient.entitycommand&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.entityclient.entitycommand&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.entityclient.entitycommand&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.createcommand&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.close&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.begintransaction(system.data.isolationlevel)&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.begintransaction&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.storeconnection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.connectionstate&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.connectionstate&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.state&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.serverversion&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.datasource&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.database&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.componentmodel.component&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.componentmodel.icontainer&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.componentmodel.component.container&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.connectiontimeout&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entityconnection.connectionstring&vendor=Microsoft&topicVersion=110&topicLocale=EN-US

  • 8/16/2019 Curs EntityFramework

    27/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 27

    with the Connection set to this

    EntityConnection.

    CreateObjRefCreates an object that contains all the relevant

    information required to generate a proxy used to

    communicate with a remote object.

    GetMetadataWorkspace Returns the MetadataWorkspace associated with

    this EntityConnection.

    GetSchema(String)Returns schema information for the data source

    of this DbConnection using the specified string

    for the schema name.

    Open, OpenAsyncEstablishes a connection to the data source by

    calling the underlying data provider's Open

    method.

    Exemplul cu EntityConnection, EntityCommand si EntityDataReader.

    Console.WriteLine("Test EntityConnection, EntityCommand siEntityDataReader");using (var conn = new EntityConnection("Name = Model1Container")){

    conn.Open();// Interogare MetadataWorkSpace pentru a obtine EntitySet  MetadataWorkspace workspace = conn.GetMetadataWorkspace();var sets = from  container in 

     workspace.GetItems(DataSpace.CSpace)from  set in container.BaseEntitySets

     where set is EntitySet select set;

    #region Afisare EntitySet din MetadataWorkSpaceforeach (EntitySet set in sets){

    Console.WriteLine(set.ElementType.Name);}#endregion 

    string eSQL = "SELECT VALUE (c) FROM Model1Container.Customers AS c “ + “ where c.CustomerId > 1";

    using (EntityCommand  command = new EntityCommand (eSQL, conn)){

    EntityDataReader reader =command.ExecuteReader(CommandBehavior.SequentialAccess);

     while(reader.Read()){ // coloana 1 contine Name din Customer. 

    Console.WriteLine("Name = " + reader.GetString(1));}}

    }

    http://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entitycommand.connection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entitycommand.connection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entitycommand.connection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.marshalbyrefobject.createobjref(system.type)&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.getmetadataworkspace&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.getmetadataworkspace&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.metadata.edm.metadataworkspace&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.metadata.edm.metadataworkspace&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.metadata.edm.metadataworkspace&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.common.dbconnection.getschema(system.string)&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.common.dbconnection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.common.dbconnection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.common.dbconnection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.open&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.open&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.common.dbconnection&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.common.dbconnection.getschema(system.string)&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=t%3asystem.data.metadata.edm.metadataworkspace&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.data.entityclient.entityconnection.getmetadataworkspace&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=m%3asystem.marshalbyrefobject.createobjref(system.type)&vendor=Microsoft&topicVersion=110&topicLocale=EN-UShttp://ms-xhelp//?method=page&id=p%3asystem.data.entityclient.entitycommand.connection&vendor=Microsoft&topicVersion=110&topicLocale=EN-US

  • 8/16/2019 Curs EntityFramework

    28/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 28

    Clasa EntityConnectionStringBuilder

    Furnizeaza o modalitate de a crea si gestiona continutul stringului de conexiune folosit de

    EntityClient.

     Exemplu

    // Specify the provider name, server and database.

    string providerName = "System.Data.SqlClient";

    string serverName = ".";

    string databaseName = "AdventureWorks";

    // Initialize the connection string builder for the

    // underlying provider. 

    SqlConnectionStringBuilder sqlBuilder =new  SqlConnectionStringBuilder();

    // Set the properties for the data source.

    sqlBuilder.DataSource = serverName;

    sqlBuilder.InitialCatalog = databaseName;

    sqlBuilder.IntegratedSecurity = true;

    // Build the SqlConnection connection string.

    string providerString = sqlBuilder.ToString();

    // Initialize the EntityConnectionStringBuilder. 

    EntityConnectionStringBuilder entityBuilder =

    new  EntityConnectionStringBuilder();

    //Set the provider name. 

    entityBuilder.Provider = providerName;

    // Set the provider-specific connection string. 

    entityBuilder.ProviderConnectionString = providerString;

    // Set the Metadata location. 

    entityBuilder.Metadata = @"res://*/AdventureWorksModel.csdl|

    res://*/AdventureWorksModel.ssdl|

    res://*/AdventureWorksModel.msl" ;

    Console.WriteLine(entityBuilder.ToString());

    using (EntityConnection conn =

    new EntityConnection(entityBuilder.ToString()))

    {

    conn.Open();

    Console.WriteLine("Just testing the connection.");

    conn.Close();

  • 8/16/2019 Curs EntityFramework

    29/75

    Topici speciale .NET – Entity Framework 2016 

    Ioan Asiminoaei – Facultatea de Informatica – Universitatea “Al. I. Cuza” Iasi  Page 29

    }

    Clasa EntityCommand

    Reprezinta o comanda pentru nivelul conceptual.

    Constructorii sunt asemanatori cu cei de la clasa Command din ADO.NET.

    Pot avea ca parametrii: fraza SQL; conexiunea; tranzactia.

    Metodele mai