Upload
karl-slade
View
223
Download
0
Embed Size (px)
Citation preview
8/9/2019 What is Entity Framework
1/48
P a g e | 1
What is Entity Framework?First question that comes to the mind is what is an entity framework?
Microsoft has given following definition:
The Microsoft ADO.NET Entity Framework is an Object/Relational Mappin !ORM" framework thatenables #e$elopers to work with relational #ata as #omain%specific objects& eliminatin the nee# formost of the #ata access pl'mbin co#e that #e$elopers 's'ally nee# to write. (sin the EntityFramework& #e$elopers iss'e )'eries 'sin *+N,& then retrie$e an# manip'late #ata as stron ly type#objects. The Entity Framework-s ORM implementation pro$i#es ser$ices like chan e trackin & i#entityresol'tion& la y loa#in & an# )'ery translation so that #e$elopers can foc's on their application%specific b'siness lo ic rather than the #ata access f'n#amentals.
To simply say it: Entity framework is an Object/ elational Ma!!ing "O/ M# framework$ %t is anenhancement to &'O$(E) that gives develo!ers an automated mechanism for accessing * storing the
data in the database and working with the results in addition to 'ata eader and 'ata+et$
(ow the question is what is O/ M framework and why do we need it?
O M is a tool for storing data from domain objects to relational database like M+ +,- +erver in anautomated way without much !rogramming$ O/ M includes three main !arts: 'omain class objects.
elational database objects and Ma!!ing information on how domain objects ma!s to relational databaseobjects "tables. views * stored!rocedures#$ O M hel!s us to kee! our database design se!arate from our
domain class design$ )his makes a!!lication maintainable and e tendable$ %t also automates standard0 1' o!eration "0reate. ead. 1!date * 'elete# so develo!er doesn2t need to write it manually$
For more info visit: htt!://en$wiki!edia$org/wiki/Object3relational4ma!!ing
)here are many O M frameworks for $net in the market like 'ataObjects$(et. (5ibernate. O!en&ccess.+ub+onic etc$ Entity Framework is an o!en source O M framework from Microsoft$
Entity Framework ArchitectureFollowing figure shows the overall architecture of the Entity Framework$ -et2s see each com!onent of thearchitecture:
http://en.wikipedia.org/wiki/Object-relational_mappinghttp://en.wikipedia.org/wiki/Object-relational_mapping
8/9/2019 What is Entity Framework
2/48
P a g e | 2
EDM (Entity Data Model): E'M consist three main !arts3 0once!tual model. Ma!!ing and +toragemodel$
Conceptual Model: 0once!tual model is your model classes and their relationshi!s$ )his will beinde!endent from your database table design$
tora!e Model: +torage model is your database design model which includes tables. views. stored !rocedures and their relationshi!s and keys$
Mappin!: Ma!!ing consist information about how your conce!tual model is ma!!ed to storage model$
"#$% to Entities: -%(, to Entities is query language used to write queries against the object model$ %treturns entities which are defined in the conce!tual model$ 6ou can use your -%(, skills here$
Entity %": Entity +,- is again a query language same as -%(, to Entities$ 5owever it is little moredifficult than -7E and also develo!er need to learn it se!arately$
8/9/2019 What is Entity Framework
3/48
P a g e | 3
&' ect er ice: Object service is a main entry !oint for accessing data from database and to return it back$ Object service is res!onsible for materiali8ation which is !rocess of converting data returned fromentity client data !rovider "ne t layer# to an entity object structure$
Entity Client Data *ro ider: )he main res!onsibility of this layer is to convert -7E or Entity +,-queries into +,- query which is understood by underlying database$ %t communicates with &'O$(et data !rovider which in turn sends or retrieves data from database$
AD&+$et Data *ro ider: )his layer communicates with database using standard &'O$(et$
Setup EntityFramework Environment:%nstall the following for the basic tutorials:
• .NET Framework 4.5/Visual Stu io !"#!
• $S S%& Server !""5/!""'/!"#! E(press
Setting up the database
)his tutorial will use sam!le +chool'9 which has different tables. stored !rocedures and view$
Following is +chool'9 database design:
8/9/2019 What is Entity Framework
4/48
P a g e | 4
• One-to-One: Stu ent an Stu ent) ress *as one+to+one relations*ip eg. Stu ent*as ,ero or one Stu ent) ress.
• One-to-Many: Stan ar an Tea-*er *as one+to+many relations*ip eg. many Tea-*ers -an e asso-iate wit* one Stan ar .
• Many-to-Many: Stu ent an ourse *as many+to+many relations*ip using
Stu ent ourse ta le w*ere Stu ent ourse ta le in-lu es Stu ent0 an ourse0 . Soone stu ent -an 1oin many -ourses an one -ourse also -an *ave many stu ents.
+am!le !roject contains +chool'9$mdf which you can attach to your local +,- server 7 ; database$
reate Entity 2ata $o el in EntityFramework 5."
8/9/2019 What is Entity Framework
5/48
P a g e | 5
5ere. we are going to create Entity 'ata Model "E'M# for +chool'9 database and understand basic building blocks$
6ou can create entity data model for e isting database in Entity Framework ;$ the same way as youcreated it in Entity Framework
8/9/2019 What is Entity Framework
6/48
P a g e | 6
>$ Entity 'ata Model Bi8ard in +7 =7 o!ens with four o!tions to select$ EF Desi!ner ,rom data'ase isfor database first a!!roach. Empty EF Desi!ner model for model first a!!roach. Empty Code Firstmodel and Code First ,rom data'ase is for code first a!!roach$ Be will focus of database first a!!roachin the basic tutorials so select EF Desi!ner ,rom data'ase o!tion and click $e-t
8/9/2019 What is Entity Framework
7/48
P a g e | 7
8/9/2019 What is Entity Framework
8/48
P a g e | 8
;$ %n this ste!. you need to choose the version of Entity Framework$ Be will use Entity Framework ;$ inthe basic tutorials so select Entity Framework ;$ and click (e t$
8/9/2019 What is Entity Framework
9/48
P a g e | 9
C$ )his ste! will dis!lay all the )ables. iews and +tored Drocedures in the database$ +elect tables. views
and +Ds you want. kee! the default checkbo es selected and click Finish$ 6ou can change Model (ames!ace if you want$
$ote:
*lurali.e or sin!ulari.e !enerated o' ect names checkbo singulari8e entityset name if table name inthe database is !lural eg$ %f +chool'9 has +tudents table name then entityset would be singular +tudent$+imilarly relationshi!s between the model will be !lurali8e if table has one3to3many or many3to3manyrelationshi! with other table$ Eg$ +tudent has many3to3many relationshi! with course table so +tudententity set will have !lural !ro!erty name 0ourses for the collection of courses$
second checkbo . #nclude ,orei!n key columns in the model includes foreign key !ro!erty e !licitly tore!resent the foreign key$ For e am!le. +tudent table has one3to3many relationshi! with +tandard table$+o every student is associated with only one standard$ )o re!resent this in the model. +tudent entitysetincludes +tandard%d !ro!erty with +tandard navigation !ro!erty$ %f this checkbo is unchecked then it willonly include +tandard !ro!erty but not +tandard%d in +tudent entityset$
)hird checkbo . #mport selected stored procedures and ,unctions into entity model automaticallycreates Function %m!orts for the stored !rocedures and functions$ 6ou don2t need to manyally im!ort it asyou had to do it !rior to Entity Framework ;$ $
8/9/2019 What is Entity Framework
10/48
P a g e | 10
$ &fter clicking on AFinish2. it will add +chool$edm file into your !roject$
O!en E'M designer by double clicking on +chool$edm that dis!lays all the entities for selected tablesand relation between them as below:
8/9/2019 What is Entity Framework
11/48
P a g e | 11
+o this way you can create sim!le E'M from your e isting database$
(ow let2s see all the building blocks of generated E'M "+chool$edm # as shown in above figure$
Entity/Ta'le Mappin!:
Each entity in E'M is ma!!ed with database table$ 6ou can check entity3table ma!!ing by right click onany entity in the E'M designer 3@ select )able Ma!!ing$ &lso. if you change any !ro!erty name of entityfrom designer then table ma!!ing would reflect that automatically$
8/9/2019 What is Entity Framework
12/48
P a g e | 12
Conte-t 0 Entity Classes:
Every Entity 'ata Model generates one conte t class and multi!le entity classes for each '9 table$E !and +chool$edm and see two im!ortant files. GE'M (ameH$0onte t$tt and GE'M (ameH$tt:
8/9/2019 What is Entity Framework
13/48
P a g e | 13
chool+Conte-t+tt: )his )< tem!late file generates conte t class whenever you change Entity 'ata Model"$edm file#$ 6ou can see conte t class file by e !anding +chool$0onte t$tt$ 0onte t class resides inGE'M (ameH$conte t$cs file$ 'efault conte t class name is G'9 (ameH I Entities eg$ 0onte t classname for our +chool'9 is +chool'9Entities$ 0onte t class is derived from '90onte t class in EntityFramework ;$ $ Drior to EF ;$ . it used to derive from Object0onte t$
8/9/2019 What is Entity Framework
14/48
P a g e | 14
chool+tt: +chool$tt is )< tem!late file that generates entity classes for each '9 tables$ Entity classes areDO0O "Dlain Old 0- Object# classes that can be !ro y classes "we will see later what is !ro y classes#$
EDM Desi!ner: E'M designer re!resents your conce!tual model$ %t consist Entities. associations *multi!licity between the entities$ %nitially it will e actly look like your database table structure but youcan add or merge columns or remove columns which are not required by your a!!lication from thisdesigner$ Even you can add new object in this model which can have columns from different databasetables from conte t menu as shown in above figure$ emember. whatever changes you do here it should
be ma!!ed with storage model$ +o you have to be careful while doing any changes in the designer$
6ou can o!en this E'M designer in JM- view where you can see all the three !art of E'M3 0once!tualschema "0+'-#. +torage schema "++'-# and ma!!ing schema "M+-#. together in JM- view$
8/9/2019 What is Entity Framework
15/48
P a g e | 15
ight click on +chool$edm 3@ click AO!en with$$2. this will o!en !o!u!$ +elect AJM- "te t# Editor2 in the !o!u!$ isual +tudio cannot dis!lay the model in 'esign view and in JM- at the same time. so you willsee a message asking whether it2s OK to close the 'esign view of the model$ 0lick 6es$ )his will o!enJM- view$ 6ou can see following JM- view by toggling all outlining
6ou can see ++'- content. 0+'- content and 03+ ma!!ing content here$ %f you e !and ++'- and0+'-. each one has some common JM- node under each schema node$ 6ou don2t need to edit ml
because you can do it in the Model 9rowser$
Model 1rowser: O!en Model 9rowser by right clicking on the E'M 'esigner and select Model 9rowser from conte t menu:
Model browser contains all the information about the E'M. its conce!tual model. storage model andma!!ing information$
8/9/2019 What is Entity Framework
16/48
P a g e | 16
EntityContainer Entity0ontainer is a wra!!er for Entity+ets and &ssociation+ets$ %t is critical entry !ointfor querying the model$
Entity et: Entity+et is a container for Entity)y!e$ %t is set of same entityty!e$ 6ou can think it like dbtable$
8/9/2019 What is Entity Framework
17/48
P a g e | 17
EntityType: Entity)y!e is a dataty!e in the model$ 6ou can see each Entity)y!e for your conce!tualmodel in JM-$ %f you e !and Entity)y!e node in JM-. you can see each !ro!erties and its ty!e andother info$
Association et: &ssociation+et defines the relation between each Entity+et$
Types o, Entity in Entity Framework:)here was four ty!es of Entities in Entity Framework # DO0O Dro y"dnamic !ro y#
8/9/2019 What is Entity Framework
18/48
P a g e | 18
DO0O entity should meet the following requirement to become DO0O !ro y:
=$ & custom data class must be declared with !ublic access$
7$ & custom data class must not be sealed "(ot%nheritable in isual 9asic#
>$ & custom data class must not be abstract "Must%nherit in isual 9asic#$
8/9/2019 What is Entity Framework
19/48
P a g e | 19
Netting the actual entity ty!e from a dynamic !ro y:
6ou can use Object0onte t$NetObject)y!e"# to find actual ty!e of dynamic !ro y as below:
Entity can have two ty!es of !ro!erties. +calar !ro!erties and (avigation !ro!erties$
calar properties are !ro!erties whose actual values are contained in the entity$ For e am!le. +tudententity has scalar !ro!erties e$g$ +tudent%d. +tudent(ame$ )hese corres!onds with the +tudent tablecolumns$
$a i!ation properties are !ointers to other related entities$ )he +tudent has +tandard !ro!erty asnavigation !ro!erty that will enable a!!lication to navigate from a +tudent to related +tandard entity$
%uerying wit* E2$:6ou can query E'M mainly by three ways. =# -%(, to Entities 7# Entity +,- ># (ative +,-
3) "#$% to Entities: -7E query synta is easier to learn than Entity +,-$ 6ou can use your -%(, skillsfor querying with E'M$ )here are two ty!es of synta you can use with -%(,3to3Entities. -%(, Method+ynta with -amda e !ression and -%(, query synta $
"#$% Method synta-(lamda e-pression):
8/9/2019 What is Entity Framework
20/48
P a g e | 20
&&'uer ing #it LIN' to ntities
using (%ar conte*t " ne# Sc oolD+ ntities()) { %ar L, 'uer " conte*t!Students!# ere(s "> s!StudentName "" -+ill.); } "#$% %uery synta-:
using (%ar conte*t " ne# Sc oolD+ ntities())
{ %ar L, 'uer " /rom st in conte*t!Students # ere st!StudentName "" 0+ill0 select st; }First. you have to create object of conte t class which is +chool'9Entities$ 6ou should initiali8e it inusing"# so that once it going out of using sco!e then it will automatically call 'is!ose"# method of'b0onte t$ %n both the synta above. conte t returns %,ueryable$
Be will learn different ty!es of -%(, to Entities query in !rojection query cha!ter later$
4) Entity %": Entity +,- is another way to create a query$ %t is !rocessed by the Entity Framework2sObject +ervices directly$ %t returns Object,uery instead of %,ueryable$
6ou need Object0onte t to create query using Entity +,-$
Following -o e snippet s*ows same 3uery result as &!E 3uery a ove.
&&'uer ing #it 1b2ect Ser%ices and ntit S'L string s3lString " 0S L C4 5AL6 st 7819 Sc oolD+ ntities!Students 0 : 0AS st $ 8 st!StudentName "" +ill 0;
%ar ob2ct* " (ct* as I1b2ectConte*tAdapter)!1b2ectConte*t;
1b2ect'uer student " ob2ct*!Create'uer (s3lString); Student ne#Student " student!7irst();
ou -an also use Entity onne-tion an Entity omman to e(e-ute Entity S%& as elow:
using (%ar con " ne# ntit Connection(0name"Sc oolD+ ntities0)) { con!1pen(); ntit Command cmd " con!CreateCommand(); cmd!Command4e*t " 0S L C4 5AL6 st 7819 Sc oolD+ ntities!Students as st # erest!StudentName" +ill 0; Dictionar dict " ne# Dictionar ();
8/9/2019 What is Entity Framework
21/48
8/9/2019 What is Entity Framework
22/48
P a g e | 22
$o el First evelopment wit* EntityFrameworkModel First: %n Model First a!!roach. you create Entities. relationshi!s. and inheritance hierarchies
directly on the design surface of E'MJ$ +o in Model First a!!roach. when you add &'O$(E) Entity'ata Model. you should select Empty EF Desi!ner model $
6ou can create entity. association and inheritance on em!ty designer using toolbo $
8/9/2019 What is Entity Framework
23/48
P a g e | 23
&fter creating required entities. associations and inheritance on design surface of the em!ty model. youcan use designer2s conte t menu o!tion Nenerate database from model to generate ''- scri!t$
+elect e isting database connection from wi8ard and then it will dis!lay ''- for the entities$
8/9/2019 What is Entity Framework
24/48
P a g e | 24
+o this is called Model First a!!roach$
2ata ase First evelopment wit* EntityFramework 4."Be have already seen this a!!roach in 0reate Entity 'ata Model where we created model and classesfrom e isting database$ +o when you generate E'MJ from e isting database then it is a 'atabase Firsta!!roach$
http://www.entityframeworktutorial.net/EntityFramework5/create-dbcontext-in-entity-framework5.aspxhttp://www.entityframeworktutorial.net/EntityFramework5/create-dbcontext-in-entity-framework5.aspxhttp://www.entityframeworktutorial.net/EntityFramework5/create-dbcontext-in-entity-framework5.aspx
8/9/2019 What is Entity Framework
25/48
P a g e | 25
Eager &oa ing:Eager loading is the !rocess whereby a query for one ty!e of entity also loads related entities as !art ofthe query$ Eager loading is achieved using #nclude method of %,ueryable$
9elow code sni!!et shows eager loading where +tandard entity will also be loaded with +tudent entityusing %nclude method:
L !" "ue#y Synta$:
using (%ar conte*t " ne# Sc oolD+ ntities()) { %ar res " (/rom s in conte*t!Students!Include(0Standard0) # ere s!StudentName "" 0StudentB0 select s)!7irst1rDe/ault(); }
L !" Method Synta$:
using (%ar ct* " ne# Sc oolD+ ntities()) { stud " ct*!Students!Include(s "> s!Standard) ! ere(s "> s!StudentName ""0StudentB0)!7irst1rDe/ault();
&& ou can also pass entit name as a string 0Standard0 && stud " ct*!Students!Include(0Standard0) ! ere(s "> s!StudentName ""0StudentB0)!7irst1rDe/ault(); } &bove code will result in following +,- query:
S L C4 41 (B)*tentBE! StudentIDE AS StudentIDE=*tentBE! StudentNameE AS StudentNameE=*tent,E! StandardIdE AS StandardIdE=*tent,E! StandardNameE AS StandardNameE=*tent,E! DescriptionE AS DescriptionE
7819 dboE! StudentE AS *tentBE L 74 164 8 F1IN dboE! StandardE AS *tent,E 1N *tentBE! StandardIdE "
*tent,E! StandardIdE $ 8 StudentB " *tentBE! StudentNameE "oad multiple le els o, related entities:
8/9/2019 What is Entity Framework
26/48
P a g e | 26
6ou can also eagerly load multi!le levels of related entities$ 9elow code sni!!et loads related +tudent.+tandard and )eachers:
using (%ar ct* " ne# Sc oolD+ ntities())
{ stud " ct*!Students! ere(s "> s!StudentName "" 0StudentB0) !Include(s "> s!Standard!4eac ers)!7irst1rDe/ault(); } &bove code results in following +,- query:
S L C4 ro2ect,E! StudentIDE AS StudentIDE=
ro2ect,E! StudentNameE AS StudentNameE=ro2ect,E! StandardIdE AS StandardIdE=ro2ect,E! StandardNameE AS StandardNameE=ro2ect,E! DescriptionE AS DescriptionE=ro2ect,E! CBE AS CBE=ro2ect,E! 4eac erIdE AS 4eac erIdE=ro2ect,E! 4eac erNameE AS 4eac erNameE=ro2ect,E! StandardIdBE AS StandardIdBE
7819 ( S L C4LimitBE! StudentIDE AS StudentIDE=LimitBE! StudentNameE AS StudentNameE=LimitBE! StandardIdBE AS StandardIdE=LimitBE! StandardNameE AS StandardNameE=LimitBE! DescriptionE AS DescriptionE=
ro2ectBE! 4eac erIdE AS 4eac erIdE=ro2ectBE! 4eac erNameE AS 4eac erNameE=ro2ectBE! StandardIdE AS StandardIdBE=
CAS $ N ( ro2ectBE! 4eac erIdE IS N6LL) 4$ N CAS4(N6LL AS int) LS B NDAS CBE 7819 (S L C4 41 (B) *tentBE! StudentIDE AS StudentIDE= *tentBE!
StudentNameE AS StudentNameE= *tentBE! StandardIdE AS StandardId,E= *tent,E!StandardIdE AS StandardIdBE= *tent,E! StandardNameE AS StandardNameE= *tent,E!DescriptionE AS DescriptionE
7819 dboE! StudentE AS *tentBE L 74 164 8 F1IN dboE! StandardE AS *tent,E 1N *tentBE! StandardIdE "
*tent,E! StandardIdE $ 8 updated student " *tentBE! StudentNameE ) AS LimitBE L 74 164 8 F1IN (S L C4
*tent@E! 4eac erIdE AS 4eac erIdE=*tent@E! 4eac erNameE AS 4eac erNameE=*tent@E! StandardIdE AS StandardIdE
7819 dboE! 4eac erE AS *tent@E $ 8 *tent@E! StandardIdE IS N14 N6LL ) AS ro2ectBE 1N LimitBE!
StandardId,E " ro2ectBE! StandardIdE ) AS ro2ect,E 18D 8 +G ro2ect,E! StudentIDE ASC= ro2ect,E! StandardIdE ASC= ro2ect,E! CBEASC
"a.y "oadin!:One of the im!ortant functionality of Entity Framework is la8y loading$ -a8y loading means delaying theloading of related data until you s!ecifically request it$ For e am!le. +tudent class contains+tudent&ddress as com!le !ro!erty$ +o conte t first loads all the students from the database then it willload address of !articular student when we access +tudent&ddress !ro!erty as below$
8/9/2019 What is Entity Framework
27/48
P a g e | 27
using (%ar ct* " ne# Sc oolD+ ntities()) { ct*!Con/iguration!LaH Loading nabled " true;
&&Loading students onl IList studList " ct*!Students!4oList();
Student std " studList E;
&&Loads Student address /or particular Student onl (seperate S'L 3uer ) StudentAddress add " std!StudentAddress; }
&bove code will result in two +,- query$ First. it will fetch all students:
S L C4*tentBE! StudentIDE AS StudentIDE=*tentBE! StudentNameE AS StudentNameE=*tentBE! StandardIdE AS StandardIdE
7819 dboE! StudentE AS *tentBE
&nd then sends following query when we get the reference of +tudent&ddress:
e*ec sp e*ecutes3l N S L C4
*tentBE! StudentIDE AS StudentIDE=*tentBE! AddressBE AS AddressBE=*tentBE! Address,E AS Address,E=*tentBE! Cit E AS Cit E=*tentBE! StateE AS StateE
7819 dboE! StudentAddressE AS *tentBE $ 8 *tentBE! StudentIDE " J ntit Ke 5alueB =N J ntit Ke 5alueB
int =J ntit Ke 5alueB"B
5owever. you can also turn off la8y loading for !articular !ro!erty or entire conte t$ )o turn off la8yloading for !articular !ro!erty. do not make it virtual$ )o turn off la8y loading for all entities in theconte t. set its configuration !ro!erty to false:
public Sc oolD+ ntities() base(0name"Sc oolD+ ntities0)
{ t is!Con/iguration!LaH Loading nabled " /alse; }
2ules ,or la.y loadin!:
=$ context.Configuration.ProxyCreationEnabled should be true$
7$ context.Configuration.LazyLoadingEnabled should be true$
8/9/2019 What is Entity Framework
28/48
P a g e | 28
>$ 0om!le !ro!erty should be defined as virtual$ 0onte t will not do la8y loading if the !ro!erty isnot define as virtual$
E(pli-it &oa ing wit* 2 onte(t
Even with la8y loading disabled it is still !ossible to la8ily load related entities. but it must be done withan e !licit call$ 1se -oad method of '9EntityEntry object$
Following code e !licitly loads +tandard of !articular +tudent using eference"# method of'bEntityEntry:
using (%ar conte*t " ne# Sc oolD+ ntities())
{ &&Disable LaH loading
conte*t!Con/iguration!LaH Loading nabled " /alse; %ar student " (/rom s in conte*t!Students
# ere s!StudentName "" 0+ill0 select s)!7irst1rDe/ault();
conte*t! ntr (student)!8e/erence(s "> s!Courses)!Load(); }%f you run above code. you can see that first it loads student but not standard as below:
-oad method get +tandard entity as below:
8/9/2019 What is Entity Framework
29/48
P a g e | 29
&bove code e ecute two different database queries$ First query is to get +tudent and second query to getstandard$
"oad collection:
1se collection method instead of eference method to load collection navigation !ro!erty$ Followinge am!le loads courses of student$
using (%ar conte*t " ne# Sc oolD+ ntities())
{ conte*t!Con/iguration!LaH Loading nabled " /alse;
%ar student " (/rom s in conte*t!Students # ere s!StudentName "" 0+ill0 select s)!7irst1rDe/ault();
conte*t! ntr (student)!Collection(s "> s!Courses)!Load(); }
$ote: The "oad e-tension method works ust like To"ist e-cept that it a oids the creation o, the listalto!ether+
8/9/2019 What is Entity Framework
30/48
P a g e | 30
D1Conte-t:&s you have seen in !revious cha!ter. E'M generates 0onte t class and Entity classes$ )his conte t classis derived from System.Data.Entity.DbContext class$
'b0onte t is a !rimary class that is res!onsible for interacting with data as object$ %t often referred to asconte t$ %t does following activities:
• %ueryin!: %t can be useful in querying the database$ %t converts database values into entityobjects and vica versa$
• Chan!e Trackin!: %t kee!s track of changes occurred in the entities after it has been queryingfrom the database$
• *ersistin! Data: %t also !erform %nsert. u!date and delete o!eration to the database based on theentity states$
Drior to EntityFramework
8/9/2019 What is Entity Framework
31/48
P a g e | 31
*u'lic Methods:
Method!a%e
&etu#n 'ype (es)#iption *$a%p+e
Entry67 1e-t8
DBEntityEntry 9ets a2 EntityEntryo 1e-t or t*egiven entityprovi inga--ess toin ormationa out t*eentity an t*ea ility toper orm a-tionson t*e entity.
Entry met*o returns 2 EntityEntry o 1e-t opasse entity o 1e-t t*roug* w*i-* we -an-*ange its state; -urrentValues anoriginalValues.
t(.Entry6Stu entEntity8.State <System.2ata.EntityState.$o i=e >
t(.Entry6Stu entEntity8. urrentValues.SetValues6Stu entEntity2T78>
t(.Entry6Stu entEntity8.7riginalValues.SetValues6Stu entEntity2T78>
Entry?TEntity@6
TEntity8
2 EntityEntry? TEntity@
9ets a2 EntityEntry?
TEntity@ o 1e-tor t*e given
entity provi inga--ess toin ormationa out t*eentity an t*ea ility toper orm a-tionson t*e entity.
Same as Entry met*o ut t*is generi- met*ooes type -*e-k o passe Entity7 1e-t e ore
returning DBEntityEntry o 1e-t
Set6Type8 DBSet Aeturns a2 Set or t*espe-i=e type;t*is allows
AB2operations to
e per ormeor t*e given
entity in t*e-onte(t.
AB2 operation.
-t(.Set6stu .9etType68. aseType8.) 6stu entEntity8>-t(.Set6stu .9etType68. aseType8.)tta-*6stu entEntity8>-t(.Set6stu .9etType68. aseType8.Aemove6stu entEntity8>
var result <-t(.Set6stu entEntity.9etType68. aseType8.S3l%uery6Csele-t D rom stu entC8>
stu entEntity.9etType68 will return P7 7 Pro(ytype.stu entEntity.9etType68. aseType s*oul e useto get an a-tual entity type.
8/9/2019 What is Entity Framework
32/48
P a g e | 32
Set?TEntity@68
2 Set Aeturns a2 Set or t*espe-i=e type;t*is allows
AB2operations to
e per ormeor t*e givenentity in t*e-onte(t.
AB2 operation.
-onte(t.Set?Stu ent@68.) 6stu entEntity8>-onte(t.Set?Stu ent@68.)tta-*6stu entEntity8
>-onte(t.Set?Stu [email protected] entEntit
y8>var result < -onte(t.Set68.S3l%uery6Csele-t Drom stu entC8>
Save *anges68
int Saves all-*anges ma ein t*is -onte(tto t*eun erlying
ata ase.
Save -*anges to t*e ata ase:
2 -onte(t.Save *anges68>
*rotected Methods:
Method !a%e &etu#n 'ype (es)#iption
S*oul Vali ateEntity
bool E(tension point allowing t*e user to overri e t*ee ault e*avior o vali ating only a e an
mo i=e entities.
Vali ateEntity 2 EntityVali ationAesult
E(tension point allowing t*e user to -ustomi,evali ation o an entity or =lter out vali ation results.
alle y 9etVali ationErrors68.
*u'lic *roperties:
,#ope#ty!a%e
&etu#n 'ype (es)#iption
*angeTra-ker
DBChangeTracker Provi es a--ess to eatures o t*e -onte(t t*at eal wit*-*ange tra-king o entities.
on=guration
2 onte(t on=guration
Provi es a--ess to -on=guration options or t*e -onte(t.
2ata ase Database reates a ata ase instan-e or t*is -onte(t an allows
you to per orm -reation; eletion or e(isten-e -*e-ks ort*e un erlying ata ase.
isit M+'( for more information of '90onte t class$
http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspxhttp://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx
8/9/2019 What is Entity Framework
33/48
P a g e | 33
Persisten-e in Entity Framework-earn how to !ersist an entity so that it either inserts new row or u!dates an e isting row or delete ane isting row in the database$
Be need to consider two scenarios. connected scenario and disconnected scenario$
Connected cenario: 0onnected scenario is when an entity is retrieved from the database and !ersistusing same conte t$ 0onte t object doesn2t destroy between when entity retrival and !ersistence$
(is)onne)ted S)ena#io: 2is-onne-te s-enario is w*en an entity is retrieve rom t*e
ata ase an mo i=e using i erent -onte(ts. 2is-onne-te s-enario is -omple( e-ausenew -onte(t oesn t know anyt*ing a out mo i=e entity so you *ave to tell -onte(t t*atw*at *as -*ange in entity. 0n t*e elow =gure; -lient retrieve entity grap* using onte(t #an t*en it per orm some B2 6-reate; up ate; 2elete8 operations an t*en it saves entitygrap* using onte(t !. onte(t ! oesn t know w*i-* operation *as een per orme on t*eentity grap* in t*is s-enario.
8/9/2019 What is Entity Framework
34/48
P a g e | 34
C27D &peration in Connected cenario:
0 1' o!eration in connected scenario is fairly easy task because conte t automatically detact changesha!!ened in the entity !rovided &uto'etect0hangesEnabled is true by default$
Following e am!le show how you can add. u!date and delete entity using conte t and callconte t$+ave0hanges"# method to u!date the database$
using (%ar conte*t " ne# Sc oolD+ ntities())
{ %ar studentList " conte*t!Students!4oList();
&& er/orm create operation conte*t!Students!Add(ne# Student() { StudentName " 0Ne# Student0 });
&& er/orm 6pdate operation Student student4o6pdate " studentList! ere(s "> s!StudentName ""0studentB0)!7irst1rDe/ault(); student4o6pdate!StudentName " 0 dited studentB0;
&& er/orm delete operation conte*t!Students!8emo%e(studentList! lementAt( ));
&& *ecute Inser= 6pdate Delete 3ueries in t e database conte*t!Sa%eC anges(); }
8/9/2019 What is Entity Framework
35/48
8/9/2019 What is Entity Framework
36/48
P a g e | 36
Student stud ;
&& ?et student /rom D+ using (%ar ct* " ne# Sc oolD+ ntities()) { stud " ct*!Students! ere(s "> s!StudentName "" 0Ne#StudentB0)!7irst1rDe/ault(); }
&& c ange student name in disconnected mode (out o/ D+Conte*t scope) i/ (stud O" null) { stud!StudentName " 06pdated StudentB0; }
&&sa%e modi/ied entit using ne# D+Conte*t using (%ar dbCt* " ne# Sc oolD+ ntities()) { &&9arP entit as modi/ied dbCt*! ntr (stud)!State " S stem!Data! ntit State!9odi/ied;
dbCt*!Sa%eC anges(); }
&s you see in the above code sni!!et. we are doing following ste!s:
=$ Net the e isting student
7$ 0hange student name out of '90onte t sco!e "disconnected mode#
>$ Be !ass modified entity into Entry method to get its '9EntityEntry object and then marking itsstate as Modified
8/9/2019 What is Entity Framework
37/48
P a g e | 37
Be will see how to add single +tandard entity:
&& create ne# Standard entit ob2ect
%ar ne#Standard " ne# Standard();
&& Assign standard name ne#Standard!StandardName " 0Standard B0;
&&create D+Conte*t ob2ect using (%ar dbCt* " ne# Sc oolD+ ntities()) { &&Add standard ob2ect into Standard D+set dbCt*!Standards!Add(ne#Standard); && call Sa%eC anges met od to sa%e standard into database dbCt*!Sa%eC anges(); } &s you can see in above code sni!!et. first we have created new +tandard entity object and set
+tandard(ame to +tandard = $ +econd. created new '90onte t object and added newly created +tandardentity into +tandards Entity+et$ )hird. calling +ave0hanges method of '90onte t which sends insertquery to the database$
)his will result in following +,- query to the database:
e*ec sp e*ecutes3l N insert dboE! StandardE( StandardNameE= DescriptionE)
%alues (J = null) select StandardIdE /rom dboE! StandardE # ere JJ81 C16N4 > and StandardIdE " scope identit () =N J%arc ar(Q ) =J " Standard B <ernatively. we can also add +tandard entity into '90onte t$Entry and mark it as &dded which result insame insert query:
dbCt*! ntr (ne#Standard)!State " S stem!Data! ntit State!Added; +o this way you can add single entity$
%n the ne t cha!ter we will learn how to add entities which has one3to3one relationshi!$
2elete Entity using 2 onte(tBe used Entry"# method of 'b0onte t to mark Entity+tate to Modified in the !revious cha!ter$ +ame waywe can use Entry"# method to attach disconnected entity to the conte t and mark its state to 'eleted$
8/9/2019 What is Entity Framework
38/48
P a g e | 38
using (%ar conte*t " ne# Sc oolD+ ntities())
{ conte*t! ntr (disconnected4eac er)!State " S stem!Data! ntit State!Deleted;
conte*t!Sa%eC anges(); }
&bove code results in following delete query which deletes the row from )eacher table$
delete dboE! 4eac erE # ere ( 4eac erIdE " J ) =N J int =J "B
on-urren-y in Entity Framework:Entity Framework su!!orts O!timistic 0oncurrency by default$ %n the o!timistic concurrency. EF savesthe entity to the database in the ho!e that the same data has not changed since the entity was loaded$ %f it
finds that data has changed then an e ce!tion is thrown and you must resolve the conflict beforeattem!ting to save it again$
-et s see how you can handle o!timistic concurrency with +tudent entity$
First of all. you need to have rowversion column in the +tudent table %n order to handle concurrency with+tuent entity$ owversion is is a dataty!e in +,- +erver that automatically generates unique binary
number whenever insert or u!date o!eration !erformed in a table$ )he rowversion dataty!e is just anincrementing number$ owevesion is synonym for the timestam! dataty!e$ 9oth are same$
0reate new column ow ersion in +tudent table with timestam! dataty!e as below:
8/9/2019 What is Entity Framework
39/48
P a g e | 39
$ote: alue of ow ersion will be added and u!dated automatically by the databse in %nsert and1!dateo!eration$
(ow. create new Entity 'ata Model or u!date an e isting data model by right clicking on designer 3@7pdate Model From Data'ase 3@ efresh +tudent table$ +o now. you will see ow ersion !ro!ertyadded in the +tudent entity$
(ow. you need to a!!ly concurrency mode to ,i-ed by right clicking on 2ow8ersion !ro!erty in the+tudent entity "right click on ow ersion !ro!erty not +tudent entity# 3@ select Dro!erty$ 0hange0oncurrency Mode to Fi ed from (one in the !ro!erty window as below:
EF will now include ow ersion column in the where clause whenever you do u!date o!eration and ifrowversion value is different than in where clause then it will throw D'7pdateConcurrencyE-ection $
Following code shows that 1ser= and 1ser7 get the same student and u!date +tudent(ame at the sametime:
Student studentB it 6serB " null;Student studentB it 6ser, " null;
&&6ser B gets student using (%ar conte*t " ne# Sc oolD+ ntities()) { conte*t!Con/iguration! ro* Creation nabled " /alse;
8/9/2019 What is Entity Framework
40/48
P a g e | 40
studentB it 6serB " conte*t!Students! ere(s "> s!StudentID ""B)!Single(); } &&6ser , also get t e same student using (%ar conte*t " ne# Sc oolD+ ntities()) { conte*t!Con/iguration! ro* Creation nabled " /alse; studentB it 6ser, " conte*t!Students! ere(s "> s!StudentID ""
B)!Single(); } &&6ser B updates Student name studentB it 6serB!StudentName " 0 dited /rom userB0;
&&6ser , updates Student name studentB it 6ser,!StudentName " 0 dited /rom user,0;
now. 1ser= saves his changes before 1ser7$ +o when user7 trys to save the changes. he will getconcurrency e ection:
&&6ser B sa%es c anges /irst
using (%ar conte*t " ne# Sc oolD+ ntities()) { tr { conte*t! ntr (studentB it 6serB)!State " ntit State!9odi/ied; conte*t!Sa%eC anges(); } catc (Db6pdateConcurrenc *ception e*) { Console! riteLine(01ptimistic Concurrenc e*ception occured0); } }
&&6ser , sa%es c anges a/ter 6ser B!&&6ser , #ill get concurrenc e*ection&&because Create1r9odi/iedDate is di//erent in t e databaseusing (%ar conte*t " ne# Sc oolD+ ntities())
{ tr { conte*t! ntr (studentB it 6ser,)!State " ntit State!9odi/ied; conte*t!Sa%eC anges(); } catc (Db6pdateConcurrenc *ception e*) { Console! riteLine(01ptimistic Concurrenc e*ception occured0); } }Concurrency in Code/First:
6ou can create timestam! !ro!erty in code3first by usng Q)imestam!R attribute$ Make sure !ro!erty ty!eis byteQR because timestam! is binary in 0S$
4imestampE
public b te E 8o#5ersion { get; set; }
8/9/2019 What is Entity Framework
41/48
P a g e | 41
EF includes !ro!erty in where clause in u!date o!eration if the !ro!erty is marked with)imestam!attribute$
6ou can resolve concurrency e ection many ways$ isit msdn on detailed information on how to resolveo!timistic concurrency$
'ownload sam!le !roject for concurrency demo$
'ownload sam!le !roject for the demo$
Entity Framework 9+ #ntroduction:Belcome to Entity Framework C tutorials section$ 5ere. you will learn about new features introduced inEntity Framework C$ with isual +tudio 7 =7$
Entity Framework C$ has introduced many new e citing features for database first "designer# and code3first a!!roaches$
Features ,or Data'ase First (Desi!ner) and Code/First 1oth:
=$ 0onnection resiliency
7$ &synchronous query and save
>$ 0ode3based configuration
8/9/2019 What is Entity Framework
42/48
P a g e | 42
==$ 0reating conte t with an o!en connection
=7$ %m!roved !erformance and warm3u! time
Features ,or Code/First:
=$ 0ustom conventions
7$ %nsert. u!date * delete stored !rocedures for entity 01' o!eration
>$ %nde attribute "EF C$=#
8/9/2019 What is Entity Framework
43/48
P a g e | 43
Console! riteLine(07inis ed ?etStudent!!!0);
}
return student; }
&s you can see in the above code. Net+tudent method marked with async to make it asynchronous$eturn ty!e of asynchrounous method must be Task $ Net+tudent returns object of +tudent entity so returnty!e must be Task; tudent< $
&lso. query is marked with await . this freed calling thread to do something else till it e ecutes query andreturns data$ Be have used FirstOr'efault&sync e tension method of +ystem$'ata$Entity$ you may useother e tension methods a!!ro!riately like +ingleOr'efault&sync. )o-ist&syn etc$
Asynchronous a e:
6ou can call conte t$+ave0hanges asynchronously the same way as async query:
Transa-tion support:Entity Framework by default wra!s %nsert. 1!date or 'elete o!eration in a transaction whenever youe ecute +ave0hanges"#$ EF starts new transaction for each o!erations and com!lete the transaction whenit o!eration finishes$ Bhen you e ecute another such o!eration a new transaction is started$
EF C has introduced data'ase+1e!inTransaction and Data'ase+7seTransaction to !rovide more controlover transaction$ (ow. you can e ecute multi!le o!erations in a single transaction as below:
using (S stem!Data! ntit !DbConte*t4ransaction db4ran "conte*t!Database!+egin4ransaction( )) { tr { Student stdB " ne# Student() { StudentName " 0ne#student0 }; conte*t!Students!Add(stdB); conte*t!Database! *ecuteS3lCommand( J06 DA4 Student S 4 StudentName " dited Student Name 0 : 0 $ 8 StudentID "B0 ); conte*t!Students!8emo%e(stdB);
&&sa%es all abo%e operations #it in one transaction conte*t!Sa%eC anges();
&&commit transaction
8/9/2019 What is Entity Framework
44/48
P a g e | 44
db4ran!Commit(); } catc ( *ception e*) { &&8ollbacP transaction i/ e*ception occurs db4ran!8ollbacP(); }
}database$1se)ransaction allows the 'b0onte t to use a transaction which was started outside of theEntity Framework$
2 Set.) Aange G 2 Set.AemoveAange:'b+et in EF C has introduced new methods &dd ange * emove ange$ 'b+et$&dd ange addscollection"%Enumerable# of entities to the 'b0onte t. so you don t have to add each entity individually$
IList ne#Students " ne# List(); ne#Students!Add(ne# Student() { StudentName " 0StudentB b addrange0 }); ne#Students!Add(ne# Student() { StudentName " 0Student, b addrange0 }); ne#Students!Add(ne# Student() { StudentName " 0Student@ b addrange0 });
using (%ar conte*t " ne# Sc oolD+ ntities()) { conte*t!Students!Add8ange(ne#Students); conte*t!Sa%eC anges(); }+ame way. use 'b+et$ emove ange to remove collection of entities from 'b+et$
IList e*istingStudents " M!!
using (%ar conte*t " ne# Sc oolD+ ntities())
{ conte*t!Students!8emo%e8ange(e*istingStudents); conte*t!Sa%eC anges(); }
ustom o e+First onventions:0ode First has a set of default behaviours for the models that refer to as conventions$ EF C !rovidesability to define your own custom conventions which will be default behaviour for your models$
)here are two main ty!es of 0onventions. 0onfiguration 0onventions and Model 0onventions$
Con,i!uration Con entions:
8/9/2019 What is Entity Framework
45/48
P a g e | 45
0onfiguration 0onventions are a way to configure entities without overriding default behaviour !rovidedin the Fluent &D%$ 6ou can define a configuration convention inside your OnModel0reating event or in acustom 0onvention 0lass in a similar way to how you would define normal entity ma!!ings with theFluent &D%$
For e am!le. you can define !rimary key of entity that has !ro!erty named Gentity nameH 4%'$ E$g$+tudent4%' !ro!erty of +tudent entity will be !rimary key:
protected o%erride %oid 1n9odelCreating(Db9odel+uilder model+uilder) { model+uilder ! roperties() ! ere(p "> p!Name "" p!Declaring4 pe!Name : 0 ID0) !Con/igure(p "> p!IsKe ());
base!1n9odelCreating(model+uilder);
}Following e am!le show how to set string length of 'escri!tion !ro!erty in all entities:
protected o%erride %oid 1n9odelCreating(Db9odel+uilder model+uilder) { model+uilder ! roperties() ! ere(p "> p!Name "" 0Description0) !Con/igure(p "> p!$as9a*Lengt (, ));
base!1n9odelCreating(model+uilder); }6ou can also define custom class for this convention by deriving 0onvention class as below:
public class KCon%ention Con%ention { public KCon%ention() { ! roperties() ! ere(p "> p!Name "" p!Declaring4 pe!Name : 0 ID0) !Con/igure(p "> p!IsKe ());
} }0onfigure custom convention as below:
protected o%erride %oid 1n9odelCreating(Db9odel+uilder model+uilder)
{ model+uilder!Con%entions!Add< KCon%ention>(); }Model Con entions:
8/9/2019 What is Entity Framework
46/48
P a g e | 46
Model 0onventions is based on the underlying model metadata$ )here are conventions for 0+'- and++'- both$ 0reate class that im!lements %0once!tualModel0onvention form 0+'- conventions andim!lement %+toreModel0onvention for ++'- convention$
isit code!le documentation for more information$
'ownload code3first sam!le !roject for custom conventions demo$
Code First / #nsert= 7pdate= Delete tored*rocedure Mappin!:Entity Framework C 0ode First !rovides ability to create and use stored !rocedure for add. u!date anddelete o!eration$ %t was not !ossible in the !revious versions of Entity Framework$
tudent Entity:
class Student { public Student() { }
public int Student ID { get; set; } public string StudentName { get; set; } }
Following e am!le automatically create stored !rocedure for +tudent entity using Fluent &D%$
protected o%erride %oid 1n9odelCreating(Db9odel+uilder model+uilder)
{ model+uilder! ntit () !9ap4oStored rocedures(); }
&bove code will create three !rocedures +tudent4%nsert. +tudent41!date and +tudent4'elete$+tudent4%nsert and +tudent41!date stored !rocedures has !arameters name corres!onds to the !ro!ertynames$ +tudent4'elete will have !rimary key !ro!erty +tudent%' !arameter$
https://entityframework.codeplex.com/wikipage?title=Custom%20Conventionshttps://entityframework.codeplex.com/wikipage?title=Custom%20Conventionshttps://entityframework.codeplex.com/wikipage?title=Custom%20Conventionshttp://www.entityframeworktutorial.net/EntityFramework6/sample-project.aspxhttps://entityframework.codeplex.com/wikipage?title=Custom%20Conventionshttp://www.entityframeworktutorial.net/EntityFramework6/sample-project.aspx
8/9/2019 What is Entity Framework
47/48
P a g e | 47
6ou can also change stored !rocedure and !arameters name as below:
protected o%erride %oid 1n9odelCreating(Db9odel+uilder model+uilder) { model+uilder! ntit () !9ap4oStored rocedures(p "> p!Insert(sp ">sp!$asName(0sp InsertStudent0)! arameter(pm "> pm!StudentName= 0name0)!8esult(rs ">rs!Student ID= 0Student ID0)) !6pdate(sp "> sp!$asName(0sp 6pdateStudent0)! arameter(pm ">pm!StudentName= 0name0)) !Delete(sp "> sp!$asName(0sp DeleteStudent0)! arameter(pm ">pm!Student ID= 0Id0)) ); }
%f you want all your entities to use stored !rocedures then do as following:
protected o%erride %oid 1n9odelCreating(Db9odel+uilder model+uilder)
{
model+uilder!4 pes()!Con/igure(t "> t!9ap4oStored rocedures()); }
"imitations:
• Only Fluent &D% can be used to ma! stored !rocedures$ 6ou cannot use 'ata &nnotation attributesin EF C for stored !rocedure ma!!ing$
• 6ou cannot use mi ture of stored !rocedure and query to add. u!date and delete o!eration on thesame entity$ 6ou can either use stored !rocedure or +,- query for all add. u!date and deleteo!eration with entity$
'ownload sam!le !roject for demo$
isit code!le documentation for more information$
Previous
Ne(t
0n e( )ttri ute:
http://www.entityframeworktutorial.net/EntityFramework6/sample-project.aspxhttps://entityframework.codeplex.com/wikipage?title=Code%20First%20Insert%2FUpdate%2FDelete%20Stored%20Procedure%20Mappinghttps://entityframework.codeplex.com/wikipage?title=Code%20First%20Insert%2FUpdate%2FDelete%20Stored%20Procedure%20Mappinghttps://entityframework.codeplex.com/wikipage?title=Code%20First%20Insert%2FUpdate%2FDelete%20Stored%20Procedure%20Mappinghttp://www.entityframeworktutorial.net/EntityFramework6/sample-project.aspxhttps://entityframework.codeplex.com/wikipage?title=Code%20First%20Insert%2FUpdate%2FDelete%20Stored%20Procedure%20Mapping
8/9/2019 What is Entity Framework
48/48
P a g e | 48
Entity Framework C !rovides %nde attribute to create %nde on !articular column in the database as below:
class Student { public Student()
{ }
public int Student ID { get; set; } public string StudentName { get; set; }
Inde*E public int 8egistrationNumber { get; set; } }9y default. %nde name will be %J4G!ro!erty nameH$ 5owever. you can also change %nde name$
6ou can also make it 0lustered inde by s!ecifying IsClustered = true and unique inde by s!ecifying IsUni ue=true $
Inde*( 0IND U 8 ?N690= IsClustered"true= Is6ni3ue"true )E public int 8egistrationNumber { get; set; }