+ All Categories
Home > Documents > C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda,...

C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda,...

Date post: 04-Jan-2020
Category:
Upload: others
View: 8 times
Download: 0 times
Share this document with a friend
47
Entity Framework 17.01.2012 1/47 Ioan Asiminoaei Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi Despre ce vom discuta? Entity Framework Notiuni introductive despre modele de programare cu baze de date; Notiuni introductive despre Entity Framework Anatomia unei aplicatii cu EF Exemple
Transcript
Page 1: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 1/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Despre ce vom discuta?

Entity Framework

Notiuni introductive despre modele de programare cu

baze de date;

Notiuni introductive despre Entity Framework

Anatomia unei aplicatii cu EF

Exemple

Page 2: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 2/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Modele de programare – cu baze de date

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 si

memorare este facut pe baza modelului conceptual, model ce reflecta obiectele problemei

de rezolvat.

3. ADO.NET clasic presupune DataReader / DataAdapter pentru a citi inf din bd si

Command pentru a executa insert, update, delete, etc.

4. Cu EF randurile si coloanele din tabele sunt returnate ca obiecte si nu mai folosim in mod

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

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

Modeling (ERM).

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

unui obiect, dar nu si comportarea. Entitatea este asemanatoare cu schema unei tabele din baza

de date numai ca aceasta descrie schema obiectelor problemei de rezolvat (schema obiectelor

afacerii).

ERM apare pentru prima data in lucrarea lui Dr. Peter Chen: “The Entity-Relationship

Model—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.

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

creeaza trei fisiere : csdl, msl, ssdl.

Articolele descrise de un EDM se numesc entitati.

Clasele ce sunt generate din entitatile modelului precum si obiectele instantiate din acestea se

numesc de asemenea entitati sau clase entitati sau obiecte entitati.

Intre entitati pot exista relatii, identificate prin proprietati de navigare.

Sursa de date (Baza de date)

Baza de date pe care o folosim nu are impact asupra modelului. Putem folosi Oracle, SqlServer,

Firebird, etc. Comunicarea cu baza de date se face prin furnizorii de ADO.NET pentru baza de

date respectiva. Avem nevoie sa identificam providerul si stringul de conexiune la baza de date ;

cu aceste informatii EF va reactualiza baza de date.

Page 3: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 3/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Trasaturi EF : API si utilitare

Metadata

1. Proiectare – mai intai baza de date

Wizard pentru EDM pleaca de la bd existenta si creaza un model. Se pot selecta tabelele ce vor fi

incluse in model.

2. Proiectare – modelul mai inati si apoi baza de date

ASP.NET cu MVC foloseste acest model care nu e definitivat complet.

VS 2010 permite crearea modelului mai intai si apoi generarea bazei de date.

Vom discuta in continuare numai despre metoda de creare a bazei de date ca fiind prima

etapa si apoi proiectarea modelului conceptual.

Schema de mai jos arata relatiile dintre diferitele componente ale unei aplicatii ce foloseste EF.

Object Services

ObjectServices furnizeaza functionalitatea necesara de a lucra cu obiecte din entitati.

Clasa EntityObject gestioneaza orice clasa mostenita din aceasta:

• rezultate cereri ;

• gestionare modificari si relatii dintre obiecte ;

• salvarea modificarilor in baza de date ;

• serializare (XML si binar).

Page 4: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 4/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Jurnalizare modificari

Dupa ce a fost instantiat un obiect entitate, ObjectServices gestioneaza toate modificarile

suferite de acesta si le va folosi atunci cand se cere salvarea datelor in baza de date.

ObjectServices construieste comenzile Insert, Update, Delete pentru fiecare obiect

adaugat, modificat sau sters.

Gestiune relatii si chei straine (Foreign Keys)

EDM designer genereaza aceste relatii plecand de la structura bazei de date.

Data Binding

Entitatile pot fi utilizate ca surse de date pentru contraole din Windows Forms si WPF.

Dezvoltare n-Tier

EntityClient

EntityClient este API principal din EF. Furnizeaza functionalitatea de a lucra cu cereri si

comenzi, regasire rezultate. EntityClient este folosit in special pentru a obtine date folosite in

rapoarte. Datele raportate de EntityClient sunt in forma tabelara (read only) in timp ce

Object Services va transforma aceste date create de EntityClient in obiecte.

EF si servicii WCF

Dataset

EF foloseste DataReader in forma EntityDataReader ce mosteneste DbDataReader.

O cerere cu EntityClient returneaza un DataReader.

Clasele EntityConnection, EntityCommand, EntityDataReader asemanatoare cu

DbConnection, DbCommand, DbDataReader.

Entity Data Model (EDM)

Un EDM poate fi vazut ca legatura dintre aplicatie si baza de date.

EDM ne da posibilitatea de a lucra cu modelul conceptual al datelor si nu cu schema bazei de

date.

EDM este folosit pentru orice interactiune cu baza de date pentru a regasi date sau a le salva.

Modelul conceptual, modelul de memorare si maparile dintre cele doua sunt definite in fisiere

bazate pe scheme XML si au urmatoarele extensii:

Page 5: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 5/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

• Conceptual schema definition language (CSDL) – defineste modelul conceptual. CSDL

este implementarea EF pentru Entity Data Model (EDM). Extensia fisierului este .csdl.

• Store schema definition language (SSDL) – defineste modelul de memorare, care mai

este numit si modelul logic. Extensia fisierului este .ssdl.

• Mapping specification language (MSL) – defineste maparile dintre modelul de memorare

sic el conceptual. Extensia fisierului este .msl.

Observatie

Modelul de memorare si maparile pot fi schimbate fara a fi nevoie sa schimbam modelul

conceptual, clasele de date sau cod din aplicatie. Din cauza ca modelul de memorare este specific

furnizorului bazei de date, se poate lucra cu modelul conceptual pe diferite tipuri de surse de

date.

EF foloseste acest model si fisierele de mapare pentru operatii de creare, citire, actualizare si

stergere plecand de la entitati spre sursa de date.

Maparea obiectelor la date

In general unei tabele ii corespunde o singura clasa si relatiile dintre clase sunt reprezentate

adesea in mod diferit fata de relatiile dintre tabele. De exemplu pentru a reprezenta un client

pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa

Customer, in timp ce o inregiustrare din baza de date din tabela Order contine o coloana “foreign

key” cu o valoare ce corespunde la valoarea unei chei primare din tabela Customer. Clasa

Customer poate sa aiba o proprietate numita Orders, ce contine o colectie de instante a clasei

Order, in timp ce in tabela Customer din baza de date nu exista o asemenea coloana.

O rezolvare a acestei probleme o constituie maparea claselor si proprietatilor la tabelele si

coloanele tabelelor.

EF mapeaza tabelele relationale, coloanele si cheile straine din modelul logic la entitati si relatii

in modelul conceptual.

Utilitarele pentru EDM (Entity Data Model) genereaza clase extensibile bazate pe modelul

conceptual. Acestea sunt clase partiale si pot fi extinse de catre dezvoltator. Implicit, clasele care

sunt generate pentru un model conceptual particular sunt derivate din clasele de baza ce

furnizeaza servicii pentru materializarea entitatilor ca obicte si pentru gestionarea si salvarea

modificarilor effectuate. Dezvoltatorul foloseste aceste clase pentru a lucra cu entitatile si

relatiile ca obiecte relationate prin asocieri. Aceste clase pot fi personalizate de catre dezvoltator.

Accesare si modificare date din entitati

EF foloseste informatiile din model si fisierele de mapare pentru a translata cererile asupra

obiectelor din modelul conceptual in cereri specifice sursei de date.

EF furnizeaza urmatoarele modalitati de a interoga modelul conceptual si a returna obiecte:

Page 6: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 6/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

• LINQ to Entities. Furnizeaza suport pentru Language-Integrated Query (LINQ) in

vederea interogarii tipurilor de entitati definite in modelul conceptual.

• Entity SQL. Un dialect SQL independent de mediul de memorare ce lucreaza direct cu

entitatile in modelul conceptual.

• Metode de constructie a cererilor folosind LINQ.

EF include furnizorul de date EntityClient, furnizor ce gestioneaza conexiunile, parseaza

cererile asupra entitatilor in cereri specifice sursei de date si returneaza un data reader folosit de

EF pentru a materialize datele din obiecte.

Urmatoarea diagrama (MSDN) ilustreaza arhitectura EF pentru accesarea datelor:

Utilitarele pentru EDM pot genera o clasa derivata din ObjectContext ce reprezinta un

container in modelul conceptual. ObjectContext furnizeaza facilitate pentru gestionarea si

salvarea modificarilor din entitati, concurenta si relatiile dintre obiecte.

Metoda SaveChanges din aceasta clasa efectueaza operatiile de insert, update si delete asupra

sursei de date.

Page 7: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 7/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Furnizori de date

Provider-ul EntityClient extinde modelul ADO.NET prin accesarea datei in termenii

modelului conceptual al entitatilor si relatiilor. In final EntityClient comunica cu baza de

date.

Utilitar pentru Entity Data Model

Impreuna cu EF runtime, .NET 4.0 include un utilitar EDM Generator (EdmGen.exe) ce permite

conectarea la baza de date si genereaza modelul si fisierele de mapare bazate pe o mapare de 1-

la-1 intre entitati si tabele. Fisierul .csdl (modelul conceptual) este folosit pentru a genera clasele

ce reprezinta tipurile de entitati si ObjectContext.

Entity Data Model - Concepte

Entity Data Model (EDM) foloseste urmatoarele concepte pentru a descrie structura datei:

• tip entitate (entity type);

• tip asociere (association type);

• proprietate (property).

Entity type – descrie structura datei cu EDM – sunt construite din proprietati si constituie un

template pentru entitati (definitia unei clase este un template pentru instantele clasei).

Fiecare entitate trebuie sa aiba o cheie unica. O multime de entitati este o colectie a instantelor

tipului entitatii specificate. Multimile de entitati sunt grupate in mod logic intr-un container –

entity container. Mostenirea este suportata intre tipurile de entitati.

Tipul asociere

Un tip asociere (association type) numit simplu si asociere descrie relatiile din EDM. Asocierea

reprezinta o relatie intre doua tipuri de entitati (ex. Customer si Order). Multiplicitatea unei

asocieri poate fi 0..1 sau mai multe.

Entitatile ce folosesc asocieri pot fi accesate prin proprietatile de navigare sau prin “foreign key”.

Instantele asocierilor sunt grupate in mod logic in “entity container”.

Proprietate

Tipurile entitati contin proprietati ce definesc structura acestora. Ex. entitatea Customer poate

avea proprietatile CustomerId, Name, Address.

O proprietate poate contine tipuri primitive (string, int, Boolean, etc.) sau tipuri structurate (tipuri

complexe).

Reprezentari ale modelului conceptual

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

relatii.

Page 8: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 8/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

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

reprezentari vizuale exista un fisier XML.

Exemplu cu clasele generate din tabelele Customer, Order si OrderDetails.

Descrierele tabelelor sunt (Firebird server baze de date):

CREATE TABLE CUSTOMER ( CUSTOMERID SMALLINT NOT NULL, "NAME" CHAR(20) CHARACTER SET ISO8859_1 DEFAULT '[n/a]'

NOT NULL COLLATE ISO8859_1, ADRESA CHAR(30) CHARACTER SET ISO8859_1 DEFAULT '[n/a]'

COLLATE ISO8859_1); ALTER TABLE CUSTOMER ADD CONSTRAINT PK_CUSTOMER PRIMARY KEY (CUSTOMERID);

CREATE TABLE "ORDER" ( ORDERID SMALLINT NOT NULL, DATA DATE DEFAULT 'NOW' NOT NULL, CUSTOMERID SMALLINT NOT NULL, VALOARE DECIMAL(12, 2) DEFAULT 0.0); ALTER TABLE "ORDER" ADD CONSTRAINT PK_ORDER PRIMARY KEY (ORDERID); ALTER TABLE "ORDER" ADD CONSTRAINT FK_ORDER FOREIGN KEY (CUSTOMERID) REFERENCES CUSTOMER(CUSTOMERID);

CREATE TABLE ORDERDETAILS ( ORDERID SMALLINT NOT NULL, PRODUS CHAR(20) CHARACTER SET ISO8859_1 DEFAULT '[n/a]' NOT NULL COLLATE ISO8859_1, VALOARE DECIMAL(12, 2) DEFAULT 0.0 NOT NULL, SERIAL SMALLINT DEFAULT 0 NOT NULL); ALTER TABLE ORDERDETAILS ADD CONSTRAINT PK_ORDERDETAILS PRIMARY KEY (ORDERID,SERIAL);

Page 9: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 9/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

ALTER TABLE ORDERDETAILS ADD CONSTRAINT FK_ORDERDETAILS FOREIGN KEY (ORDERID) REFERENCES "ORDER"(ORDERID);

O parte din fisierul edmx ce descrie modelul conceptual:

<edmx:StorageModels> <Schema Namespace="Model1.Store" Alias="Self" Provider="FirebirdSql.Data.FirebirdClient" ProviderManifestToken="2.5" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl"> <EntityContainer Name="Model1StoreContainer"> <EntitySet Name="CUSTOMER" EntityType="Model1.Store.CUSTOMER" store:Type="Tables" Schema="Firebird" /> <EntitySet Name="ORDER" EntityType="Model1.Store.ORDER" store:Type="Tables" Schema="Firebird" /> <EntitySet Name="ORDERDETAILS" EntityType="Model1.Store.ORDERDETAILS" store:Type="Tables" Schema="Firebird" /> <AssociationSet Name="FK_ORDER" Association="Model1.Store.FK_ORDER"> <End Role="CUSTOMER" EntitySet="CUSTOMER" /> <End Role="ORDER" EntitySet="ORDER" /> </AssociationSet>

De observat cele trei tabele si entitati precum si modul de descriere a unei relatii data de foreign

key.

Entitatea Customer din acest fisier arata astfel :

<EntityType Name="CUSTOMER"> <Key> <PropertyRef Name="CUSTOMERID" /> </Key> <Property Name="CUSTOMERID" Type="smallint" Nullable="false" /> <Property Name="NAME" Type="char" Nullable="false" MaxLength="20" /> <Property Name="ADRESA" Type="char" MaxLength="30" /> </EntityType>

Faceti comparatie cu descrierea tabelei Customer din Firebird.

Parte din fisierul .csdl pentru acest model conceptual:

<?xml version="1.0" encoding="utf-8"?> <Schema Namespace="Model1" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm"> <EntityContainer Name="EntitiesCustomer" annotation:LazyLoadingEnabled="true"> <EntitySet Name="CUSTOMERs" EntityType="Model1.CUSTOMER" /> <EntitySet Name="ORDERs" EntityType="Model1.ORDER" /> <EntitySet Name="ORDERDETAILS" EntityType="Model1.ORDERDETAIL" />

Page 10: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 10/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

<AssociationSet Name="FK_ORDER" Association="Model1.FK_ORDER"> <End Role="CUSTOMER" EntitySet="CUSTOMERs" /> <End Role="ORDER" EntitySet="ORDERs" /> </AssociationSet> … <EntityType Name="ORDER"> <Key> <PropertyRef Name="ORDERID" /> </Key> <Property Name="ORDERID" Type="Int16" Nullable="false" /> <Property Name="DATA" Type="DateTime" Nullable="false" /> <Property Name="CUSTOMERID" Type="Int16" Nullable="false" /> <Property Name="VALOARE" Type="Decimal" Precision="12" Scale="2" /> <NavigationProperty Name="CUSTOMER" Relationship="Model1.FK_ORDER"

FromRole="ORDER" ToRole="CUSTOMER" /> <NavigationProperty Name="ORDERDETAILS"

Relationship="Model1.FK_ORDERDETAILS" FromRole="ORDER" ToRole="ORDERDETAILS" />

</EntityType> … <Association Name="FK_ORDER"> <End Role="CUSTOMER" Type="Model1.CUSTOMER" Multiplicity="1" /> <End Role="ORDER" Type="Model1.ORDER" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="CUSTOMER"> <PropertyRef Name="CUSTOMERID" /> </Principal> <Dependent Role="ORDER"> <PropertyRef Name="CUSTOMERID" /> </Dependent> </ReferentialConstraint> </Association> … </Schema>

Partial .ssdl (cuvantul store ne arata ca e vorba de modelul de memorare, baza de date, legatura

intre tabele si entitati, etc.).

<?xml version="1.0" encoding="utf-8"?> <Schema Namespace="Model1.Store" Alias="Self" Provider="FirebirdSql.Data.FirebirdClient" ProviderManifestToken="2.5" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl"> <EntityContainer Name="Model1StoreContainer"> <EntitySet Name="CUSTOMER" EntityType="Model1.Store.CUSTOMER" store:Type="Tables" Schema="Firebird" /> <EntitySet Name="ORDER" EntityType="Model1.Store.ORDER" store:Type="Tables" Schema="Firebird" /> <EntitySet Name="ORDERDETAILS" EntityType="Model1.Store.ORDERDETAILS"

store:Type="Tables" Schema="Firebird" /> …

Page 11: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 11/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

<EntityType Name="ORDER"> <Key> <PropertyRef Name="ORDERID" /> </Key> <Property Name="ORDERID" Type="smallint" Nullable="false" /> <Property Name="DATA" Type="date" Nullable="false" /> <Property Name="CUSTOMERID" Type="smallint" Nullable="false" /> <Property Name="VALOARE" Type="decimal" Precision="12"

Scale="2" /> </EntityType>

Si in final .msl. Maparea intre entitati si tabele, intre proprietati si coloane, etc.

<?xml version="1.0" encoding="utf-8"?> <Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs"> <EntityContainerMapping StorageEntityContainer="Model1StoreContainer" CdmEntityContainer="EntitiesCustomer"> <EntitySetMapping Name="CUSTOMERs"> <EntityTypeMapping TypeName="Model1.CUSTOMER"> <MappingFragment StoreEntitySet="CUSTOMER"> <ScalarProperty Name="CUSTOMERID" ColumnName="CUSTOMERID" /> <ScalarProperty Name="NAME" ColumnName="NAME" /> <ScalarProperty Name="ADRESA" ColumnName="ADRESA" /> </MappingFragment> </EntityTypeMapping> </EntitySetMapping> … </Mapping>

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

� • Store/storage metadata

� • Store/storage metadata schema

� • S-side

Page 12: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 12/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Mapping Specification Language (MSL)

� • Mapping layer

� • Mapping specification

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

Ce este 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

EntityContainer

EntitySet

EntityType

EntityContainer

Constituie punctul principal pentru a executa cereri asupra modelului.

Expune EntitySet care dau acces la obiectele pe care le contin.

EntityContainer are un atribut:LazyLoadingEnabled="true" ce indica modul de creare al

modelului (de la baza de date la model sau invers), folosit numai in fisierul EDMX.

Page 13: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 13/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

EntitySet

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

<EntitySet Name="Addresses"

EntityType="SampleModel.Address" /> <EntitySet Name="Contacts"

EntityType="SampleModel.Contact" />

EntityType

EntityType este tipul de data din model.

<EntityType Name="Address"> <Key>

<PropertyRef Name="addressID" /> </Key> <Property Name="addressID" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" /> <Property Name="Street1" Type="String" MaxLength="50" Unicode="true" FixedLength="true" />

Etc…

Elementul Key

identificator unic pentru entitate.

Elementele Property

sunt tipuri simple (tipuri primitive).

Proprietati de navigare sunt legate de asocieri.

Asocierile definesc relatiile dintre tipurile entitate. Nu definesc o relatie completa, acestea

definesc numai endpoint-urile, adica entitatile implicate in relatie si multiplicitatea lor.

Proprietatea Referential Constraint

Intr-un model ce contine chei straine, Referential Constraint defineste dependenta dintre

entitatile relationate.

Page 14: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 14/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

MSL: The Mappings

Nivelul de mapare este situat intre modelul conceptaul si cel de memorare (baza de date).

In Designer putem vedea aceste informatii.

Page 15: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 15/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Cereri cu EDM

Cereri asupra modelului nu direct asupra bazei de date

private static void QueryContacts() {

using (var context = new SampleEntities()) {

var contacts = context.Contacts; foreach (var contact in contacts) {

Console.WriteLine("{0} {1}", contact.FirstName.Trim(), contact.LastName);

} } Console.Write("Press Enter..."); Console.ReadLine();

}

Page 16: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 16/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Cereri cu Object Services si Entity SQL

namespace: System.Data.Objects

Cerere cu Entity SQL

var queryString = "SELECT VALUE c " +

"FROM SampleEntities.Contacts AS c " + "WHERE c.FirstName='Robert'";

ObjectQuery<Contact> contacts = context.CreateQuery<Contact>(queryString);

Explicatie

Cea mai simpla cerere ObjectSet<Contact> contacts = context.Contacts;

Page 17: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 17/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Exemplu complet (cu Firebird)

Analiza codului si modalitati de lucru.

In aplicatie s-a plecat de la baza de date si VS 2010 a construit modelul conceptual pentru

tabelele selectate in momentul proiectarii aplicatiei.

Atentie ! In acest cod nu trebuie sa facem modificari pentru ca acest fisier se regenereaza la

diverse modificari facute asupra modelului. Deoarece toate clasele sunt definite ca partial putem

dezvolta clasa in alt fisier. Atentie de asemenea la metodele partiale pe care le propune

designerul.

//------------------------------------------------------------------------------

// <auto-generated>

// This code was generated from a template.

//

// Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------

using System;

using System.Data.Objects;

using System.Data.Objects.DataClasses; using System.Data.EntityClient;

using System.ComponentModel;

using System.Xml.Serialization; using System.Runtime.Serialization;

[assembly: EdmSchemaAttribute()]

#region EDM Relationship Metadata

[assembly: EdmRelationshipAttribute("Model1", "FK_ORDER", "CUSTOMER",

System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Entity.CUSTOMER), "ORDER",

System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Entity.ORDER), true)]

[assembly: EdmRelationshipAttribute("Model1", "FK_ORDERDETAILS", "ORDER",

System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Entity.ORDER),

"ORDERDETAILS", System.Data.Metadata.Edm.RelationshipMultiplicity.Many,

typeof(Entity.ORDERDETAIL), true)]

#endregion

namespace Entity {

#region Contexts

/// <summary> /// No Metadata Documentation available.

/// </summary>

public partial class EntitiesCustomer : ObjectContext

{

#region Constructors

/// <summary>

/// Initializes a new EntitiesCustomer object using the connection string found

in the 'EntitiesCustomer' section of the application configuration file.

/// </summary>

public EntitiesCustomer() : base("name=EntitiesCustomer", "EntitiesCustomer")

{

this.ContextOptions.LazyLoadingEnabled = true;

OnContextCreated();

Page 18: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 18/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

}

/// <summary>

/// Initialize a new EntitiesCustomer object.

/// </summary> public EntitiesCustomer(string connectionString) : base(connectionString,

"EntitiesCustomer")

{

this.ContextOptions.LazyLoadingEnabled = true;

OnContextCreated();

}

/// <summary>

/// Initialize a new EntitiesCustomer object.

/// </summary> public EntitiesCustomer(EntityConnection connection) : base(connection,

"EntitiesCustomer")

{

this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated();

}

#endregion

#region Partial Methods

partial void OnContextCreated();

#endregion

#region ObjectSet Properties

/// <summary>

/// No Metadata Documentation available.

/// </summary> public ObjectSet<CUSTOMER> CUSTOMERs

{

get {

if ((_CUSTOMERs == null))

{

_CUSTOMERs = base.CreateObjectSet<CUSTOMER>("CUSTOMERs"); }

return _CUSTOMERs;

}

}

private ObjectSet<CUSTOMER> _CUSTOMERs;

/// <summary>

/// No Metadata Documentation available.

/// </summary>

public ObjectSet<ORDER> ORDERs

{

get

{

if ((_ORDERs == null))

{

_ORDERs = base.CreateObjectSet<ORDER>("ORDERs"); }

return _ORDERs;

}

}

Page 19: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 19/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

private ObjectSet<ORDER> _ORDERs;

/// <summary>

/// No Metadata Documentation available.

/// </summary> public ObjectSet<ORDERDETAIL> ORDERDETAILS

{

get

{

if ((_ORDERDETAILS == null))

{

_ORDERDETAILS = base.CreateObjectSet<ORDERDETAIL>("ORDERDETAILS"); }

return _ORDERDETAILS;

} }

private ObjectSet<ORDERDETAIL> _ORDERDETAILS;

#endregion #region AddTo Methods

/// <summary> /// Deprecated Method for adding a new object to the CUSTOMERs EntitySet.

Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.

/// </summary>

public void AddToCUSTOMERs(CUSTOMER cUSTOMER)

{

base.AddObject("CUSTOMERs", cUSTOMER); }

/// <summary>

/// Deprecated Method for adding a new object to the ORDERs EntitySet. Consider

using the .Add method of the associated ObjectSet&lt;T&gt; property instead.

/// </summary>

public void AddToORDERs(ORDER oRDER) {

base.AddObject("ORDERs", oRDER);

}

/// <summary>

/// Deprecated Method for adding a new object to the ORDERDETAILS EntitySet.

Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead. /// </summary>

public void AddToORDERDETAILS(ORDERDETAIL oRDERDETAIL)

{

base.AddObject("ORDERDETAILS", oRDERDETAIL);

}

#endregion

}

#endregion

#region Entities

/// <summary>

/// No Metadata Documentation available. /// </summary>

[EdmEntityTypeAttribute(NamespaceName="Model1", Name="CUSTOMER")]

[Serializable()]

[DataContractAttribute(IsReference=true)]

Page 20: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 20/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

public partial class CUSTOMER : EntityObject

{

#region Factory Method

/// <summary> /// Create a new CUSTOMER object.

/// </summary>

/// <param name="cUSTOMERID">Initial value of the CUSTOMERID property.</param>

/// <param name="nAME">Initial value of the NAME property.</param>

public static CUSTOMER CreateCUSTOMER(global::System.Int16 cUSTOMERID,

global::System.String nAME)

{ CUSTOMER cUSTOMER = new CUSTOMER();

cUSTOMER.CUSTOMERID = cUSTOMERID;

cUSTOMER.NAME = nAME; return cUSTOMER;

}

#endregion #region Primitive Properties

/// <summary> /// No Metadata Documentation available.

/// </summary>

[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]

[DataMemberAttribute()]

public global::System.Int16 CUSTOMERID

{ get

{

return _CUSTOMERID;

}

set

{

if (_CUSTOMERID != value) {

OnCUSTOMERIDChanging(value);

ReportPropertyChanging("CUSTOMERID"); _CUSTOMERID = StructuralObject.SetValidValue(value);

ReportPropertyChanged("CUSTOMERID");

OnCUSTOMERIDChanged();

} }

}

private global::System.Int16 _CUSTOMERID;

partial void OnCUSTOMERIDChanging(global::System.Int16 value);

partial void OnCUSTOMERIDChanged();

/// <summary>

/// No Metadata Documentation available.

/// </summary>

[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]

[DataMemberAttribute()]

public global::System.String NAME

{

get

{

return _NAME; }

set

{

OnNAMEChanging(value);

Page 21: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 21/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

ReportPropertyChanging("NAME");

_NAME = StructuralObject.SetValidValue(value, false);

ReportPropertyChanged("NAME");

OnNAMEChanged();

} }

private global::System.String _NAME;

partial void OnNAMEChanging(global::System.String value);

partial void OnNAMEChanged();

/// <summary>

/// No Metadata Documentation available. /// </summary>

[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]

[DataMemberAttribute()] public global::System.String ADRESA

{

get

{ return _ADRESA;

}

set {

OnADRESAChanging(value);

ReportPropertyChanging("ADRESA");

_ADRESA = StructuralObject.SetValidValue(value, true);

ReportPropertyChanged("ADRESA");

OnADRESAChanged(); }

}

private global::System.String _ADRESA;

partial void OnADRESAChanging(global::System.String value);

partial void OnADRESAChanged();

#endregion

#region Navigation Properties

/// <summary>

/// No Metadata Documentation available.

/// </summary>

[XmlIgnoreAttribute()] [SoapIgnoreAttribute()]

[DataMemberAttribute()]

[EdmRelationshipNavigationPropertyAttribute("Model1", "FK_ORDER", "ORDER")]

public EntityCollection<ORDER> ORDERs

{

get

{

return

((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ORDER>("Model1.

FK_ORDER", "ORDER");

}

set

{

if ((value != null))

{

((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ORDER>("

Model1.FK_ORDER", "ORDER", value);

}

}

Page 22: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 22/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

}

#endregion

}

/// <summary>

/// No Metadata Documentation available.

/// </summary>

[EdmEntityTypeAttribute(NamespaceName="Model1", Name="ORDER")]

[Serializable()]

[DataContractAttribute(IsReference=true)]

public partial class ORDER : EntityObject {

#region Factory Method

/// <summary>

/// Create a new ORDER object.

/// </summary>

/// <param name="oRDERID">Initial value of the ORDERID property.</param> /// <param name="dATA">Initial value of the DATA property.</param>

/// <param name="cUSTOMERID">Initial value of the CUSTOMERID property.</param>

public static ORDER CreateORDER(global::System.Int16 oRDERID, global::System.DateTime dATA, global::System.Int16 cUSTOMERID)

{

ORDER oRDER = new ORDER();

oRDER.ORDERID = oRDERID;

oRDER.DATA = dATA;

oRDER.CUSTOMERID = cUSTOMERID; return oRDER;

}

#endregion

#region Primitive Properties

/// <summary> /// No Metadata Documentation available.

/// </summary>

[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()]

public global::System.Int16 ORDERID

{

get {

return _ORDERID;

}

set

{

if (_ORDERID != value)

{

OnORDERIDChanging(value);

ReportPropertyChanging("ORDERID");

_ORDERID = StructuralObject.SetValidValue(value);

ReportPropertyChanged("ORDERID");

OnORDERIDChanged();

}

}

}

private global::System.Int16 _ORDERID; partial void OnORDERIDChanging(global::System.Int16 value);

partial void OnORDERIDChanged();

/// <summary>

Page 23: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 23/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

/// No Metadata Documentation available.

/// </summary>

[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]

[DataMemberAttribute()]

public global::System.DateTime DATA {

get

{

return _DATA;

}

set

{ OnDATAChanging(value);

ReportPropertyChanging("DATA");

_DATA = StructuralObject.SetValidValue(value); ReportPropertyChanged("DATA");

OnDATAChanged();

}

} private global::System.DateTime _DATA;

partial void OnDATAChanging(global::System.DateTime value);

partial void OnDATAChanged();

/// <summary>

/// No Metadata Documentation available.

/// </summary>

[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]

[DataMemberAttribute()] public global::System.Int16 CUSTOMERID

{

get

{

return _CUSTOMERID;

}

set {

OnCUSTOMERIDChanging(value);

ReportPropertyChanging("CUSTOMERID"); _CUSTOMERID = StructuralObject.SetValidValue(value);

ReportPropertyChanged("CUSTOMERID");

OnCUSTOMERIDChanged();

} }

private global::System.Int16 _CUSTOMERID;

partial void OnCUSTOMERIDChanging(global::System.Int16 value);

partial void OnCUSTOMERIDChanged();

/// <summary>

/// No Metadata Documentation available.

/// </summary>

[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]

[DataMemberAttribute()]

public Nullable<global::System.Decimal> VALOARE

{

get

{

return _VALOARE;

} set

{

OnVALOAREChanging(value);

ReportPropertyChanging("VALOARE");

Page 24: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 24/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

_VALOARE = StructuralObject.SetValidValue(value);

ReportPropertyChanged("VALOARE");

OnVALOAREChanged();

}

} private Nullable<global::System.Decimal> _VALOARE;

partial void OnVALOAREChanging(Nullable<global::System.Decimal> value);

partial void OnVALOAREChanged();

#endregion

#region Navigation Properties

/// <summary>

/// No Metadata Documentation available. /// </summary>

[XmlIgnoreAttribute()]

[SoapIgnoreAttribute()]

[DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("Model1", "FK_ORDER", "CUSTOMER")]

public CUSTOMER CUSTOMER

{ get

{

return

((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<CUSTOMER>("Model

1.FK_ORDER", "CUSTOMER").Value;

} set

{

((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<CUSTOMER>("Model

1.FK_ORDER", "CUSTOMER").Value = value;

}

} /// <summary>

/// No Metadata Documentation available.

/// </summary> [BrowsableAttribute(false)]

[DataMemberAttribute()]

public EntityReference<CUSTOMER> CUSTOMERReference

{ get

{

return

((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<CUSTOMER>("Model

1.FK_ORDER", "CUSTOMER");

}

set

{

if ((value != null))

{

((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<CUSTOMER>

("Model1.FK_ORDER", "CUSTOMER", value);

}

}

}

/// <summary>

/// No Metadata Documentation available.

/// </summary>

Page 25: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 25/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

[XmlIgnoreAttribute()]

[SoapIgnoreAttribute()]

[DataMemberAttribute()]

[EdmRelationshipNavigationPropertyAttribute("Model1", "FK_ORDERDETAILS",

"ORDERDETAILS")] public EntityCollection<ORDERDETAIL> ORDERDETAILS

{

get

{

return

((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ORDERDETAIL>("M

odel1.FK_ORDERDETAILS", "ORDERDETAILS"); }

set

{ if ((value != null))

{

((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ORDERDETAIL>("Model1.FK_ORDERDETAILS", "ORDERDETAILS", value);

}

} }

#endregion

}

/// <summary> /// No Metadata Documentation available.

/// </summary>

[EdmEntityTypeAttribute(NamespaceName="Model1", Name="ORDERDETAIL")]

[Serializable()]

[DataContractAttribute(IsReference=true)]

public partial class ORDERDETAIL : EntityObject

{ #region Factory Method

/// <summary> /// Create a new ORDERDETAIL object.

/// </summary>

/// <param name="oRDERID">Initial value of the ORDERID property.</param>

/// <param name="pRODUS">Initial value of the PRODUS property.</param> /// <param name="vALOARE">Initial value of the VALOARE property.</param>

/// <param name="sERIAL">Initial value of the SERIAL property.</param>

public static ORDERDETAIL CreateORDERDETAIL(global::System.Int16 oRDERID,

global::System.String pRODUS, global::System.Decimal vALOARE, global::System.Int16

sERIAL)

{

ORDERDETAIL oRDERDETAIL = new ORDERDETAIL();

oRDERDETAIL.ORDERID = oRDERID;

oRDERDETAIL.PRODUS = pRODUS;

oRDERDETAIL.VALOARE = vALOARE;

oRDERDETAIL.SERIAL = sERIAL;

return oRDERDETAIL;

}

#endregion

Observati ca anumite lucruri se repeta. Am omis, partial, codul de la OrderDetails.

Codul ce foloseste acest model poate fi urmatorul :

Page 26: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 26/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace Entity { class Program { static void Main(string[] args) { // insert in tabela Customer & afisare AddCustomer(); PrintCustomer(); PrintSpecialCustomer(); // modificare Name in Customer UpdateNameCustomer(); // Sterge Customer cu id = 2 DeleteCustomer(); Console.WriteLine("Dupa DeleteCustomer id = 2"); PrintCustomer(); Console.Read(); // insert in tabela Order & afisare AddOrder(); PrintOrderForCustomer(); PrintAllOrderWithCustomerInfo(); // OrderDetails AddOrderDetails(); PrintOrder(); Console.WriteLine("Pres Enter to exit..."); Console.ReadKey(); } // Metode pentru Customer private static void AddCustomer() { EntitiesCustomer ec = new EntitiesCustomer(); // iau max customerid din colectie int maxid = (from x in ec.CUSTOMERs select x.CUSTOMERID).Max(); Console.WriteLine("Tastati id Customer.

Maxim CustomerId = {0}", maxid); short id = Convert.ToInt16(Console.ReadLine()); CUSTOMER ct = new CUSTOMER(); ct.CUSTOMERID = id;

Page 27: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 27/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

if (ec.CUSTOMERs.Where(x => x.CUSTOMERID == ct.CUSTOMERID).Count() <= 0)

{ ct.NAME = "Name " + id.ToString(); ct.ADRESA = "Adresa " + id.ToString(); ec.AddToCUSTOMERs(ct); ec.SaveChanges(); } else Console.WriteLine("Exista CUSTOMERID = {0}",

ct.CUSTOMERID); CUSTOMER cust = CUSTOMER.CreateCUSTOMER((short)(ct.CUSTOMERID + 1),

"Name id = " + (ct.CUSTOMERID + 1).ToString()); cust.ADRESA = "Adresa " + cust.CUSTOMERID.ToString(); if (ec.CUSTOMERs.Where(x =>

x.CUSTOMERID == cust.CUSTOMERID).Count() <= 0) { ec.AddObject("EntitiesCustomer.CUSTOMERs", cust); try { ec.SaveChanges(); } catch (OptimisticConcurrencyException oex) { Console.WriteLine(

"Exceptie OptimisticConcurencyException : {0} ", oex.InnerException);

} catch (UpdateException uex) { Console.WriteLine(

"Exceptie UpdateException :{0} ", uex.InnerException);

} } else Console.WriteLine("Exista CUSTOMERID = {0}",

cust.CUSTOMERID); } private static void PrintCustomer() { EntitiesCustomer ec = new EntitiesCustomer(); foreach (CUSTOMER c in ec.CUSTOMERs) { Console.WriteLine(c.CUSTOMERID + " -> " +

c.NAME + " adr. " + c.ADRESA); } }

Page 28: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 28/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

private static void PrintSpecialCustomer() { EntitiesCustomer ec = new EntitiesCustomer(); var items = from x in ec.CUSTOMERs where (x.CUSTOMERID % 2 == 0) select new { x.CUSTOMERID, x.NAME, x.ADRESA }; Console.WriteLine("Cerere ..."); foreach (var x in items) Console.WriteLine("{0}, {1}, {2}",

x.CUSTOMERID, x.NAME, x.ADRESA); } private static void UpdateNameCustomer() { EntitiesCustomer context = new EntitiesCustomer(); EntityKey contactKey = new

EntityKey("EntitiesCustomer.CUSTOMERs", "CUSTOMERID", (short)1);

var customer = context.GetObjectByKey(contactKey); ((CUSTOMER)customer).NAME = "Nume modificat iar"; context.SaveChanges(); /* // O alta varianta EntitiesCustomer context = new EntitiesCustomer(); CUSTOMER ct = context.CUSTOMERs .First(i => i.CUSTOMERID == (short)2); ct.NAME = "Modificare nume"; context.SaveChanges(); // End * */ } /// <summary> /// Daca CUSTOMERID este folosit drept Foreign Key

intr-o alta tabela /// atunci definitia pentru ForeignKey trebuie sa fie: /// /// ALTER TABLE "ORDER" ADD CONSTRAINT FK_ORDER

FOREIGN KEY (CUSTOMERID) /// REFERENCES CUSTOMER(CUSTOMERID) ON DELETE CASCADE; /// /// </summary> private static void DeleteCustomer() { EntitiesCustomer context = new EntitiesCustomer(); CUSTOMER ct = context.CUSTOMERs .First(i => i.CUSTOMERID == (short)2); context.CUSTOMERs.DeleteObject(ct); context.SaveChanges(); }

Page 29: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 29/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

#region Order // pentru fiecare Customer adaug trei ordine

ce au id = idcustomer *10 + i, i=1,2,3 private static void AddOrder() { EntitiesCustomer ec = new EntitiesCustomer(); foreach (CUSTOMER c in ec.CUSTOMERs) { for (int i = 1; i < 4; i++) { ORDER o = new ORDER(); o.ORDERID = (short)(c.CUSTOMERID * 10 + i); o.VALOARE = o.ORDERID * 10; o.DATA = DateTime.Now.AddDays(1); o.CUSTOMERID = c.CUSTOMERID; if (ec.ORDERs.Where(x =>

x.ORDERID == o.ORDERID).Count() <= 0) { ec.AddToORDERs(o); ec.SaveChanges(); } } } } private static void PrintOrderForCustomer() { Console.WriteLine("\nSe face join intre Customer si

Order\n"); EntitiesCustomer ec = new EntitiesCustomer(); var items = from c in ec.CUSTOMERs from o in ec.ORDERs where c.CUSTOMERID == o.CUSTOMERID select new { c.CUSTOMERID, c.NAME,

o.ORDERID, o.DATA, o.VALOARE}; foreach(var x in items) Console.WriteLine("{0}, {1}, {2}, {3},

{4}",x.CUSTOMERID, x.ORDERID, x.NAME, x.DATA, x.VALOARE);

} private static void PrintAllOrderWithCustomerInfo() { Console.WriteLine("\nPrintAllOrderWithCustomerInfo\n

Se pleaca de la Order si se ajunge la Customer\n"); Console.WriteLine("\nvar items = from o in ec.ORDERs\n " + " where o.CUSTOMER.CUSTOMERID > (short)4\n " + " select new { o.ORDERID, o.CUSTOMER };\n"); EntitiesCustomer ec = new EntitiesCustomer(); var items = from o in ec.ORDERs where o.CUSTOMER.CUSTOMERID > (short)4

Page 30: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 30/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

select new { o.ORDERID, o.CUSTOMER }; foreach (var x in items) { Console.WriteLine("{0}, {1}, {2}",

x.CUSTOMER.CUSTOMERID, x.ORDERID, x.CUSTOMER.NAME); } } #endregion Order #region OrderDetails private static void AddOrderDetails() { EntitiesCustomer ec = new EntitiesCustomer(); foreach (ORDER o in ec.ORDERs) { for (int i = 1; i < 4; i++) { ORDERDETAIL od = new ORDERDETAIL(); od.ORDERID = o.ORDERID; od.PRODUS = "Produs " + i.ToString() +

o.ORDERID.ToString(); od.VALOARE = i + o.ORDERID * 10; od.SERIAL = (short)i; if (ec.ORDERDETAILS.Where(x =>

x.ORDERID == od.ORDERID && x.SERIAL == od.SERIAL).Count() <= 0)

{ ec.AddToORDERDETAILS(od); ec.SaveChanges(); } } } } private static void PrintOrder() { EntitiesCustomer ec = new EntitiesCustomer(); foreach(ORDER o in ec.ORDERs) PrintAllDetailsForOrder(o); } private static void PrintAllDetailsForOrder(ORDER o) { EntitiesCustomer ec = new EntitiesCustomer(); Console.WriteLine("\nPrintAllDetailsForOrder:

param ORDER = {0}", o.ORDERID); var items = from x in ec.ORDERDETAILS where x.ORDERID == o.ORDERID select new { o.CUSTOMER.CUSTOMERID,

Page 31: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 31/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

o.CUSTOMER.NAME, o.ORDERID, x.PRODUS }; foreach (var x in items) Console.WriteLine("{0}, {1}, {2}, {3}",

x.CUSTOMERID, x.NAME, x.ORDERID, x.PRODUS); } #endregion OrderDetails } }

Page 32: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 32/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Entity Framework Terminology - MSDN

This topic defines terms frequently referenced in Entity Framework documentation. Links are

provided to relevant topics where additional information is available.

Term Definition

association The definition of a relationship between entity types.

For more information, see Association Element (CSDL) and association type (Entity Data

Model).

association set A logical container for instances of associations of the same type.

For more information, see AssociationSet Element (CSDL) and association set (Entity Data

Model).

command tree A common, programmatic representation of all Entity Framework queries that are

composed of one or more expressions.

complex type A .NET Framework class that represents a complex property as defined in the conceptual

model. Complex types enable scalar properties to be organized within entities. Complex

objects are instances of complex types. For more information, see ComplexType Element

(CSDL) and complex type (Entity Data Model).

ComplexType The specification for a data type that represents a non-scalar property of an entity type

that does not have a key property.

conceptual

model

An abstract specification for the entity types, complex types, associations, entity

containers, entity sets, and association sets in the domain of an application in the Entity

Framework. The conceptual model is defined in CSDL in the .csdl file.

.csdl file An XML file that contains the conceptual model, expressed in CSDL.

conceptual

schema definition

language (CSDL)

An XML-based language that is used to define the entity types, associations, entity

containers, entity sets, and association sets of a conceptual model.

For more information, see CSDL Specification.

container A logical grouping of entity and association sets.

Page 33: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 33/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

concurrency A process that allows multiple users to access and change shared data at the same time.

By default, the Entity Framework implements an optimistic concurrency model.

direction Refers to the asymmetrical nature of some associations. Direction is specified

with FromRole and ToRole attributes of

a NavigationProperty orReferentialConstraint element in a schema.

For more information, see NavigationProperty Element (CSDL) and navigation property

(Entity Data Model).

.edmx file An XML file that contains the conceptual model (in CSDL), the storage model (in SSDL),

and the mappings between them (in MSL). The .edmx file is created by the Entity Data

Model Tools. For more information, see .edmx File Overview (Entity Framework).

end A participating entity in an association.

For more information, see End Element (CSDL) and association end (Entity Data Model).

entity A concept in the domain of an application from which a data type is defined.

For more information, see EntityType Element (CSDL) and entity type (Entity Data Model).

EntityClient A storage-independent ADO.NET data provider that contains classes such

as EntityConnection, EntityCommand, and EntityDataReader. Works with Entity SQL

and connects to storage specific ADO.NET data providers, such as SqlClient.

For more information, see EntityClient Provider for the Entity Framework.

entity container Specifies entity sets and association sets that will be implemented in a specified

namespace.

Entity Data

Model (EDM)

A set of concepts that describe the structure of data, as entities and relationships,

regardless of its stored form.

Entity Framework A set of technologies that supports development of data-oriented software applications

by enabling developers to work with conceptual models that are mapped to logical

schemas in data sources.

For more information, see Entity Framework Overview.

entity set A logical container for entities of a given type and its subtypes. Entity sets are mapped to

tables in a database.

Page 34: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 34/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Entity SQL A storage-independent dialect of SQL that works directly with conceptual entity schemas

and that supports conceptual model concepts such as inheritance and relationships.

For more information, see Entity SQL Language.

entity type A .NET Framework class that represents an entity as it is defined in the conceptual model.

Entity types may have scalar, complex, and navigation properties. Objects are instances of

entity types. For more information, see Object Services Overview (Entity Framework).

EntityType The specification for a data type that includes a key and a named set of properties and

represents a top-level item in a conceptual model or storage model.

For more information, see EntityType Element (CSDL) and entity type (Entity Data Model).

explicit loading When objects are returned by a query, related objects are not loaded at the same time.

By default, they are not loaded until explicitly requested using the Load method on a

navigation property. For more information, see Loading Related Objects (Entity

Framework).

foreign key

association

An association between entities that is managed through foreign key properties. For

more information, see Defining and Managing Relationships (Entity Framework).

identifying

relationship

A relationship where the primary key of the principal entity is part of the primary key of

the dependent entity. In this kind of relationship, the dependent entity cannot exist

without the principal entity. For more information, see Defining and Managing

Relationships (Entity Framework).

key The attribute of an entity type that specifies which property or set of properties is used to

identify unique instances of the entity type. Represented in the object layer by

the EntityKey class.

lazy loading When objects are returned by a query, related objects are not loaded at the same time.

Instead they are loaded automatically when the navigation property is accessed. For

more information, see Loading Related Objects (Entity Framework).

LINQ to Entities A query syntax that defines a set of query operators that allow traversal, filter, and

projection operations to be expressed in a direct, declarative way in Visual C# and Visual

Basic.

For more information, see LINQ to Entities.

mapping A specification of the correspondences between items in a conceptual model and items

Page 35: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 35/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

in a storage model.

.msl file An XML file that contains the mapping between the conceptual model and the storage

model, expressed in MSL.

mapping

specification

language (MSL)

An XML-based language that is used to map items defined in a conceptual model to

items in a storage model.

multiplicity The number of entities that can exist on each side of a relationship, as defined by an

association. Also known as cardinality.

navigation

property

A property of an entity type that represents a relationship to another entity type, as

defined by an association. Navigation properties are used to return related objects as

an EntityCollection or an EntityReference, depending on the multiplicity at the other end

of the association.

For more information, see NavigationProperty Element (CSDL) and navigation property

(Entity Data Model).

query path A string representation of a path that specifies which related objects to return when an

object query is executed. A query path is defined by calling the Include method on

an ObjectQuery.

For more information, see Loading Related Objects (Entity Framework).

object context Represents the entity container defined in the conceptual model. It contains a connection

to the underlying data source and provides services such as change tracking and identity

resolution. An object context is represented by an instance of the ObjectContext class.

object layer The entity types and object context definitions that are used by the Entity Framework.

object query A query executed within an object context against a conceptual model that returns data

as objects.

For more information, see Object Queries (Entity Framework).

object-relational

mapping

A technique for transforming data from a relational database into data types that can be

used in object-oriented software applications.

The Entity Framework provides object-relational mapping services by mapping relational

data, as defined in the storage model, to data types, as defined in the conceptual model.

Page 36: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 36/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

For more information, see Object Services Overview (Entity Framework).

Object Services Services provided by the Entity Framework that enable application code to operate on

entities like .NET Framework objects.

referential

constraint

A constraint that is defined in a conceptual model that indicates that an entity has a

dependent relationship to another entity. This constraint means that an instance of a

dependent entity cannot exist without a corresponding instance of the principle entity

For more information, see ReferentialConstraint Element (CSDL) and referential integrity

constraint (Entity Data Model).

relationship A logical connection between entities.

role The name given to each End of an association to clarify the semantics of the relationship.

For more information, see End Element (CSDL) and association end (Entity Data Model).

scalar property A property of an entity that maps to a single field in the storage model.

simple type A primitive type that is used for defining properties in the conceptual model.

For more information, see Conceptual Model Types and Entity Data Model: Primitive

Data Types.

storage model A definition for the logical model of data in a supported data source, such as a relational

database. The storage model is defined in SSDL in the .ssdl file.

For more information, see Modeling and Mapping (Entity Framework) and SSDL

Specification.

.ssdl file An XML file that contains the storage model, expressed in SSDL.

store schema

definition

language (SSDL)

An XML-based language that is used to define the entity types, associations, entity

containers, entity sets, and association sets of a storage model that frequently

corresponds to a database schema.

For more information, see SSDL Specification.

Page 37: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 37/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

C14_2012_Entity Framework (Continuare)

Object Services – (OS)

OS – reprezinta nivelul cel mai de sus pentru EF.

Object Services lucreaza direct cu obiectele instantiate (namespace System.Data.Objects) si

furnizeaza functionalitatea necesara pentru a genera si a interactiona cu obiectele din modelul

conceptual ce isi extrag datele din baza de date.

OS proceseaza cereri Linq To Entities (LtE) si ObjectQuery rezultand obiecte.

Clasa de baza ObjectContext.

Ce face Object Services?

� Proceseaza cereri;

Page 38: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 38/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

� Returneaza obiecte;

� Gestioneaza obiecte;

� Gestioneaza obiectele relatii;

� Gestioneaza starea obiectelor;

� Trimite schimbarile catre baza de date;

� Implementeaza serializarea, asocierea datelor (data binding), etc.

Procesare cereri

OS foloseste functionalitatea data de EntityClient.

Procesarea cererii implica translatare cereri Linq To Entities sau Linq Sql in cereri SQL pe care

baza de date le poate executa.

La nivelul de jos fiecare cerere este parsata intr-o « comanda arbore (command tree) » a lui

LINQ sau Linq SQL. Providerii (Oracle, Sql Server, etc.) transforma aceste comenzi in comenzi

specifice dialectului SQL recunoscut de baza de date.

« Command tree » se exprima cu entitati din modelul conceptual.

Urmatoarea figura schematizeza modul de tratare al unei cereri.

Page 39: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 39/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Observatie

De remarcat cele trei posibilitati de realizare a unei cereri si modul de executie in fiecare din

cazuri.

Vom analiza in continuare clasele importante din EF din care enumeram : ObjectContext,

ObjectSet, EntityObject, ObjectQuery.

Clasa ObjectContext

Furnizeaza facilitate pentru cereri si lucrul cu date ca obiecte ce sunt instante ale tipurilor entitate

definite in modelul conceptual.

O instanta a clasei ObjectContext contine urmatoarele :

� Conexiune la bd in forma unui obiect EntityConnection ;

� Metadata ce descrie modelul, obiect MetadataWorkspace ;

� Un obiet ObjectStateManager ce gestioneaza obiectele din cache.

EntityConnection : Contine o referinta la modelul conceptual si o conexiune la sursa de

date. Este ceva asemanator cu obiectele Connection, Command din ADO.NET.

MetadataWorkspace : poate fi folosita pentru a interactiona cu modelul conceptual in contextual

unei aplicatii date. Se pot obtine o multime de informatii la runtime.

Exemplu :

private static void MetadataWorkspaceExemplu() { Console.WriteLine("MetadataWorkspace... CSpace"); EntitiesCustomer ent = new EntitiesCustomer(); MetadataWorkspace mw = ent.MetadataWorkspace; var items = mw.GetItems<EntityType>(DataSpace.CSpace); foreach (var i in items) { Console.WriteLine("Table Name: {0}", i.Name); Console.WriteLine("Keys:"); foreach (var key in i.KeyMembers) { Console.WriteLine("{0} ({1})", key.Name,

key.TypeUsage.EdmType.FullName); } } Console.WriteLine("Metadata CSpace members..."); foreach (var i1 in items) { Console.WriteLine("Table Name: {0}", i1.Name); foreach (var key in i1.Members) { Console.WriteLine("{0} ({1})", key.Name,

key.TypeUsage.EdmType.FullName); } } }

Page 40: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 40/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Rezultatul : MetadataWorkspace... CSpace Table Name: CUSTOMER Keys:

CUSTOMERID (Edm.Int16) Table Name: ORDER Keys:

ORDERID (Edm.Int16) Table Name: ORDERDETAIL Keys:

ORDERID (Edm.Int16) SERIAL (Edm.Int16)

Metadata CSpace members... Table Name: CUSTOMER

CUSTOMERID (Edm.Int16) NAME (Edm.String)

ADRESA (Edm.String) ORDERs (Transient.collection[Model1.ORDER(Nullable=True,DefaultValue=)]) Table Name: ORDER

ORDERID (Edm.Int16) DATA (Edm.DateTime) CUSTOMERID (Edm.Int16) VALOARE (Edm.Decimal) CUSTOMER (Model1.CUSTOMER) ORDERDETAILS

(Transient.collection[Model1.ORDERDETAIL(Nullable=True,DefaultVal ue=)]) Table Name: ORDERDETAIL

ORDERID (Edm.Int16) PRODUS (Edm.String) VALOARE (Edm.Decimal) SERIAL (Edm.Int16) ORDER (Model1.ORDER)

Observatie

Examinati si alte posibilitati oferite de DataSpace var items = mw.GetItems<EntityType>(DataSpace.CSpace);

ObjectStateManager :

Mentine starea obiectelor si identitatea managementului pentru instantele tipului entitate si a

instantelor relatiilor. Este folosita de ObjectContext si nu in mod direct in aplicatie.

Revenire la ObjectContext

Clasa ce reprezinta EntityContainer este derivata din ObjectContext.

Exemplu (vezi cursul anterior):

Page 41: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 41/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

public partial class EntitiesCustomer : ObjectContext { // cod

public ObjectSet<CUSTOMER> CUSTOMERs { get { if ((_CUSTOMERs == null)) { _CUSTOMERs = base.CreateObjectSet<CUSTOMER>("CUSTOMERs"); } return _CUSTOMERs; } } private ObjectSet<CUSTOMER> _CUSTOMERs; // cod }

Metode - MSDN

Name Description

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

AddObject Adds an object to the object context.

Attach Attaches an object or object graph to the object context when the object has an

entity key.

CreateEntityKey Creates the entity key for a specific object, or returns the entity key if it already

exists.

CreateObject <T > Creates and returns an instance of the requested type .

CreateObjectSet <TEntity >()

Creates a new ObjectSet <TEntity > instance that is used to query, add, modify,

and delete objects of the specified entity type.

CreateQuery <T > Creates an ObjectQuery <T > in the current object context by using the specified

query string.

DeleteObject Marks an object for deletion.

Detach Removes the object from the object context.

DetectChanges Ensures that ObjectStateEntry changes are synchronized with changes in all

objects that are tracked by theObjectStateManager.

ExecuteFunction Executes a stored procedure or function that is defined in the data source and

Page 42: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 42/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

(String, ObjectParameter [])

expressed in the conceptual model; discards any results returned from the

function; and returns the number of rows affected by the execution.

ExecuteStoreCommand Executes an arbitrary command directly against the data source using the existing

connection.

ExecuteStoreQuery <TElement >(String,Object [])

Executes a query directly against the data source that returns a sequence of typed

results.

GetObjectByKey Returns an object that has the specified entity key.

GetObjectType Returns the entity type of the POCO entity associated with a proxy object of a

specified type.

Refresh(RefreshMode, IEnumerable)

Updates a collection of objects in the object context with data from the data

source.

Refresh(RefreshMode, Object)

Updates an object in the object context with data from the data source.

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.

Proprietati

Name Description

CommandTimeout Gets or sets the timeout value, in seconds, for all object context

operations. A null value indicates that the default value of the

underlying provider will be used.

Connection Gets the connection used by the object context.

ContextOptions Gets the ObjectContextOptions instance that contains options that

affect the behavior of the ObjectContext.

DefaultContainerName Gets or sets the default container name.

MetadataWorkspace Gets the metadata workspace used by the object context.

ObjectStateManager Gets the object state manager used by the object context to track

object changes.

QueryProvider Gets the LINQ query provider associated with this object context.

Page 43: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 43/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Evenimente

Name Description

ObjectMaterialized Occurs when a new entity object is created from data in the data source as part of a query or load operation.

SavingChanges Occurs when changes are saved to the data source.

Clasa ObjectSet

Reprezinta o entitate tipizata folosita pentru operatii de creare, citire, actualizare si stergere.

Metode (MSDN): selectie Metodele extinse nu sunt discutate.

Name Description

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

Attach Attaches an object or object graph to the object context in the current entity

set.

CreateObject () Creates a new entity type object.

CreateObject <T >()

Creates an instance of the specified type.

DeleteObject Marks an object for deletion.

Detach Removes the object from the object context.

Execute Executes the object query with the specified merge option. (Inherited

from ObjectQuery <T >.)

GroupBy Groups the query results by the specified criteria. (Inherited

from ObjectQuery <T >.)

Include Specifies the related objects to include in the query results. (Inherited

from ObjectQuery <T >.)

Intersect Limits the query results by including only the results that exist in another

object query. (Inherited from ObjectQuery <T >.)

OrderBy Orders the query results by the specified criteria. (Inherited

from ObjectQuery <T >.)

Select Limits the query results to only the properties that are defined in the

specified projection. (Inherited from ObjectQuery <T >.)

SelectValue Limits the query results to only the property specified in the

Page 44: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 44/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

<TResultType > projection. (Inherited from ObjectQuery <T >.)

Skip Orders the query results by the specified criteria and skips a specified

number of results. (Inherited from ObjectQuery <T >.)

Top Limits the query results to a specified number of items. (Inherited

from ObjectQuery <T >.)

ToTraceString Returns the commands to execute against the data source. (Inherited

from ObjectQuery.)

Union Combines the results of the query with the results of another object query,

without any duplicates. (Inherited from ObjectQuery <T >.)

UnionAll Combines the results of the query with the results of another object query,

including all duplicates. (Inherited from ObjectQuery <T >.)

Where Limits the query to results that match specified filtering criteria. (Inherited

from ObjectQuery <T >.)

Proprietati

Name Description

CommandText Returns the command text for the query. (Inherited from ObjectQuery.)

Context Gets the object context associated with this object query. (Inherited

from ObjectQuery.)

EnablePlanCaching Gets or sets a value that indicates whether the query plan should be cached. (Inherited from ObjectQuery.)

EntitySet Gets the metadata of the entity set represented by

this ObjectSet <TEntity > instance.

MergeOption Gets or sets how objects returned from a query are added to the object

context. (Inherited from ObjectQuery.)

Name Gets or sets the name of this object query. (Inherited

from ObjectQuery <T >.)

Parameters Gets the parameter collection for this object query. (Inherited

from ObjectQuery.)

ObjectQuery si LINQ to Entities

Page 45: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 45/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

ObjectQuery este clasa ce furnizeaza toate informatiile de care contextul are nevoie pentru a

executa cererea.

ObjectSet este de tip ObjectQuery si implementeaza interfata IObjectSet ce furnizeaza

functionalitatea asemanatoare colectiilor.

IObjectSet si ObjectQuery implementeaza IQueryable, ce este un tip de cerere LINQ.

IQueryable contine metadata despre cerere (expresia cererii, provider).

Observatie : sagetile nu arata corect ordinea de derivare.

IQueryable este o legatura intre ObjectSet/ObjectQuery si cererile LINQ to Entities.

Dupa ce cererea a fost executata, IQueryable expune metadata cererii si rezultatul.

Rezultatul din interiorul IQueryable este descris ca un « tip enumerabil », bazat pe interfata

IEnumerable.

Pentru ObjectQuery in MSDN :

Constructors

Name Description

ObjectQuery () Initializes a new instance of the ObjectQuery class with no initialized values.

This is the default constructor.

ObjectQuery(String) Initializes a new instance of the ObjectQuery class for a specific query

string.

ObjectQuery(String, Initializes a new instance of the ObjectQuery class for a specific query string

Page 46: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 46/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

String) and language.

Metode

Name Description

ParseQuery Parses the query string and sets the property values accordingly. If the query is valid, the

class name property and condition property of the query will be parsed. (Inherited

from ManagementQuery.)

Proprietati

Name Description

QueryString Gets or sets the query in text format. (Inherited from ManagementQuery.)

Page 47: C12 2012 Entity Framework - Alexandru Ioan Cuza …iasimin/csharp/C13_14_2012...pentru o comanda, clasa Order poate sa foloseasca o proprietate ce contine o referinta la clasa Customer,

Entity Framework 17.01.2012 47/47

Ioan Asiminoaei

Facultatea de Informatica, Universitatea “Al. I. Cuza” - Iasi

Clasa EntityObject

Tipul de baza pentru clasele generate de EDM.

MSDN

Constructors

Name Description

EntityObject Initializes a new instance of

the EntityObject class.

Metode

Name Description

OnPropertyChanged Raises the PropertyChanged event. (Inherited from StructuralObject.)

OnPropertyChanging Raises the PropertyChanging event. (Inherited from StructuralObject.)

ReportPropertyChanged Notifies the change tracker that a property has

changed. (Overrides StructuralObject .ReportPropertyChanged(String) .)

ReportPropertyChanging Notifies the change tracker that a property change is

pending. (Overrides StructuralObject .ReportPropertyChanging(String).)

SetValidValue <T >(T, T,

String)

Sets a complex object for the specified property. (Inherited

from StructuralObject.)

Proprietati

Name Description

EntityKey Gets or sets the key for this object.

EntityState Gets the entity state of the object.

Events

Name Description

PropertyChanged Occurs when a property value has changed. (Inherited from StructuralObject.)

PropertyChanging Occurs when a property value change is a pending. (Inherited

from StructuralObject.)


Recommended