Vous êtes sur la page 1sur 142

Basics of Entity Framework

1. Introduction
2. What is Entity Framework?
3. EF Architecture
4. Setup Environment
. !reate Entity "ata #ode$
%. &ypes o' Entity
(. )ueryin* with E"#
+. !ode First
,. #ode$ First
1-. "ata.ase First
11. Entity /i'ecyc$e
12. Entity 0e$ationships
13. 1ro2ection )uery
14. Ea*er /oadin*
1. /a3y /oadin*
1%. E4p$icit /oadin*
1(. "5!onte4t
1+. "5!onte4t !$ass
1,. "5Set !$ass
2-. "5EntityEntry !$ass
21. Workin* with 1roperty
22. /oca$ data
23. 0aw S)/ )uery
24. 6a$idate Entity
2. 1ersistence in EF
2%. Attach Entity 7raph
2(. Add Entity
2+. 8pdate Entity
2,. "e$ete Entity
3-. Add Entity 7raph
31. 8pdate Entity 7raph
32. !oncurrency
33. Stored 1rocedure in EF
34. !8" usin* Stored 1rocedure
3. #i*ration 'rom EF 4.4
3%. Enum Support
3(. Spatia$ "atatypes
3+. &a.$e9va$ued Function
3,. 5atch Import o' S1s
4-. #u$tip$e "ia*rams
41. !o$ored Entities
42. "own$oad Samp$e 1ro2ect
1. Introduction
:ou are *oin* to $earn EntityFramework 'rom scratch in this section. We wi$$ use EntityFramework .- with 6isua$ Studio 2-12
'or a$$ the .asic tutoria$s.

Entity Framework .- is an important re$ease .y #icroso't. It can .e used in 6isua$ Studio 2-1- and 6isua$ Studio 2-12 to write
app$ications that tar*et .;E& 4.- and .;E& 4..

Important versions history of EntityFramework:

EntityFramework
Version
Introduced Features
EF 3.5 Basic O/RM support with Database First approach.
EF 4.0 POCO Support, a!" #oa$i%&, testabi#it" i'pro(e'e%ts, custo'i!ab#e co$e &e%eratio% a%$ the Mo$e# First
approach.
EF 4.) First to a(ai#ab#e o* +u,et pac-a&e, Si'p#i*ie$ DBCo%te.t /P0 o(er Ob1ectCo%te.t, Co$e First approach. EF 4.).)
patch re#ease$ with bu& *i.i%& o* 4.).
EF 4.3 Co$e First Mi&ratio%s *eature that a##ows a $atabase create$ b" Co$e First to be i%cre'e%ta##" cha%&e$ as "our Co$e
First 'o$e# e(o#(es. EF 4.3.) patch re#ease$ with bu& *i.i%& o* EF 4.3.
EF 5.0 /%%ou%ce$ EF as Ope% Source. 0%tro$uce$ E%u' support, tab#e2(a#ue$ *u%ctio%s, spatia# $ata t"pes, 'u#tip#e2
$ia&ra's per 'o$e#, co#ori%& o* shapes o% the $esi&% sur*ace a%$ batch i'port o* store$ proce$ures, EF Power 3oo#s
a%$ (arious per*or'a%ce i'pro(e'e%ts.
EF 4.0 2 Curre%t
re#ease
EF 4.054.) is #atest re#ease o* E%tit" Fra'ewor-. 0t i%c#u$es 'a%" %ew *eaturs re#ate$ to co$e *irst 6 EF $esi&%er
#i-e as"%chro%ous 7uer" 6 sa(e, co%%ectio% Resi#ie%c", $epe%$e%c" reso#utio% etc.

6isit #S"; 'or detai$ed in'ormation on EntityFramework 6ersion <istory.

6isit Code-First Tutorial to $earn a.out EF code9'irst mode$ 'rom scratch.

rere!uisites: 5asic know$ed*e o' .;et Framework= !>= 6isua$ Studio 2--+?2-1- and #S S)/ Server is re@uired.

"udience: 5asic tutoria$s are he$p'u$ who doesnAt know anythin* a.out Entity Framework and wants to $earn it 'rom scratch.
#. $hat is Entity Framework%
First @uestion that comes to the mind is what is an entity 'ramework?
#icroso't has *iven 'o$$owin* de'initionB
The Microsoft ADO.NET Entity Framework is an Object/Relational Mappin !ORM" framework that enables #e$elopers
to work with relational #ata as #omain%specific objects& eliminatin the nee# for most of the #ata access pl'mbin
co#e that #e$elopers 's'ally nee# to write. (sin the Entity Framework& #e$elopers iss'e )'eries 'sin *+N,& then
retrie$e an# manip'late #ata as stronly type# objects. The Entity Framework-s ORM implementation pro$i#es
ser$ices like chane trackin& i#entity resol'tion& la.y loa#in& an# )'ery translation so that #e$elopers can foc's on
their application%specific b'siness loic rather than the #ata access f'n#amentals.
To simply say it: Entity 'ramework is an C.2ect?0e$ationa$ #appin* DC?0#E 'ramework. It is an enhancement to A"C.;E& that
*ives deve$opers an automated mechanism 'or accessin* F storin* the data in the data.ase and workin* with the resu$ts in
addition to "ata0eader and "ataSet.

;ow the @uestion is what is C?0# 'ramework and why do we need it?
C0# is a too$ 'or storin* data 'rom domain o.2ects to re$ationa$ data.ase $ike #S S)/ Server in an automated way without
much pro*rammin*. C?0# inc$udes three main partsB "omain c$ass o.2ects= 0e$ationa$ data.ase o.2ects and #appin*
in'ormation on how domain o.2ects maps to re$ationa$ data.ase o.2ects Dta.$es= views F storedproceduresE. C0# he$ps us to
keep our data.ase desi*n separate 'rom our domain c$ass desi*n. &his makes app$ication maintaina.$e and e4tenda.$e. It a$so
automates standard !08" operation D!reate= 0ead= 8pdate F "e$eteE so deve$oper doesnAt need to write it manua$$y.

For more in'o visitB httpB??en.wikipedia.or*?wiki?C.2ect9re$ationa$Gmappin*

&here are many C0# 'rameworks 'or .net in the market $ike "ataC.2ects.;et= ;<i.ernate= CpenAccess= Su.Sonic etc. Entity
Framework is an open source C0# 'ramework 'rom #icroso't.
&. Entity Framework "rchitecture
Fo$$owin* 'i*ure shows the overa$$ architecture o' the Entity Framework. /etAs see each component o' the architectureB


E'( )Entity 'ata (odel*: E"# consist three main parts9 !onceptua$ mode$= #appin* and Stora*e mode$.

Conceptual (odel: !onceptua$ mode$ is your mode$ c$asses and their re$ationships. &his wi$$ .e independent 'rom your
data.ase ta.$e desi*n.

+tora,e (odel: Stora*e mode$ is your data.ase desi*n mode$ which inc$udes ta.$es= views= stored procedures and their
re$ationships and keys.

(appin,: #appin* consist in'ormation a.out how your conceptua$ mode$ is mapped to stora*e mode$.

-I./ to Entities:/I;) to Entities is @uery $an*ua*e used to write @ueries a*ainst the o.2ect mode$. It returns entities which are
de'ined in the conceptua$ mode$. :ou can use your /I;) ski$$s here.

Entity +/-:Entity S)/ is a*ain a @uery $an*ua*e same as /I;) to Entities. <owever it is $itt$e more di''icu$t than /2E and a$so
deve$oper need to $earn it separate$y.

012ect +ervice:C.2ect service is a main entry point 'or accessin* data 'rom data.ase and to return it .ack. C.2ect service is
responsi.$e 'or materia$i3ation which is process o' convertin* data returned 'rom entity c$ient data provider Dne4t $ayerE to an
entity o.2ect structure.

Entity Client 'ata rovider:&he main responsi.i$ity o' this $ayer is to convert /2E or Entity S)/ @ueries into S)/ @uery which
is understood .y under$yin* data.ase. It communicates with A"C.;et data provider which in turn sends or retrieves data 'rom
data.ase.

"'0..et 'ata rovider:&his $ayer communicates with data.ase usin* standard A"C.;et.
3. +etup EntityFramework Environment:
Insta$$ the 'o$$owin* 'or the .asic tutoria$sB
.;E& Framework 4.?6isua$ Studio 2-12
#S S)/ Server 2--?2--+?2-12 E4press

Settin* up the data.ase
&his tutoria$ wi$$ use samp$e Schoo$"5 which has di''erent ta.$es= stored procedures and view.

Fo$$owin* is Schoo$"5 data.ase desi*nB
Cne9to9CneB Student and StudentAddress has one9to9one re$ationship e*. Student has 3ero or one StudentAddress.
Cne9to9#anyB Standard and &eacher has one9to9many re$ationship e*. many &eachers can .e associate with one
Standard.
#any9to9#anyB Student and !ourse has many9to9many re$ationship usin* Student!ourse ta.$e where Student!ourse
ta.$e inc$udes StudentId and !ourseId. So one student can 2oin many courses and one course a$so can have many students.

Samp$e pro2ect contains Schoo$"5.md' which you can attach to your $oca$ S)/ server 2-- data.ase.

4. Create Entity 'ata (odel in Entity Framework 4.5
<ere= we are *oin* to create Entity "ata #ode$ DE"#E 'or Schoo$"5 data.ase and understand .asic .ui$din* .$ocks.

:ou can create entity data mode$ 'or e4istin* data.ase in Entity Framework .- the same way as you created it in Entity
Framework 4.1?4.3.

/etAs do it step .y step.

1. Cpen 6isua$ Studio 2-12 and create conso$e pro2ect.


2. ;ow= add Entity "ata #ode$ .y ri*ht c$ickin* on the pro2ect in the so$ution e4p$orer 9H Add 9H c$ick ;ew Item and se$ect
A"C.;E& Entity "ata #ode$ 'rom popup= *ive ;ame ISchoo$A and c$ick Add .utton.


3. Entity "ata #ode$ Wi3ard in 6S2-12 opens with 'our options to se$ect. EF 'esi,ner from data1ase is 'or data.ase 'irst
approach=Empty EF 'esi,ner model 'or mode$ 'irst approach= Empty Code First model and Code First from data1ase is
'or code 'irst approach. We wi$$ 'ocus o' data.ase 'irst approach in the .asic tutoria$s so se$ect EF 'esi,ner from
data1ase option and c$ick .e6t


4. :ou can choose 'rom your e4istin* "5 !onnections or create new connection .y c$ickin* I;ew !onnectionA .utton. I use
e4istin* d. connection to my Schoo$"5 "ata.ase. &his wi$$ a$so add connection strin* to your app.con'i* 'i$e with de'au$t su''i4
with d. name. :ou can chan*e it i' you want. !$ick I;e4tA a'ter you set up your d. connection.


. In this step= you need to choose the version o' Entity Framework. We wi$$ use Entity Framework .- in the .asic tutoria$s so
se$ect Entity Framework .- and c$ick ;e4t.


%. &his step wi$$ disp$ay a$$ the &a.$es= 6iews and Stored 1rocedures in the data.ase. Se$ect ta.$es= views and S1s you want=
keep the de'au$t check.o4es se$ected and c$ick Finish. :ou can chan*e #ode$ ;amespace i' you want.

.ote:
1$ura$i3e or sin*u$ari3e *enerated o.2ect names check.o4 sin*u$ari3e entityset name i' ta.$e name in the data.ase is p$ura$ e*.
I' Schoo$"5 has Students ta.$e name then entityset wou$d .e sin*u$ar Student. Simi$ar$y re$ationships .etween the mode$ wi$$
.e p$ura$i3e i' ta.$e has one9to9many or many9to9many re$ationship with other ta.$e. E*. Student has many9to9many re$ationship
with course ta.$e so Student entity set wi$$ have p$ura$ property name J!oursesJ 'or the co$$ection o' courses.

second check.o4= Inc$ude 'orei*n key co$umns in the mode$ inc$udes 'orei*n key property e4p$icit$y to represent the 'orei*n key.
For e4amp$e= Student ta.$e has one9to9many re$ationship with Standard ta.$e. So every student is associated with on$y one
standard. &o represent this in the mode$= Student entityset inc$udes StandardId property with Standard navi*ation property. I'
this check.o4 is unchecked then it wi$$ on$y inc$ude Standard property .ut not StandardId in Student entityset.

&hird check.o4= Import se$ected stored procedures and 'unctions into entity mode$ automatica$$y creates Function Imports 'or
the stored procedures and 'unctions. :ou donAt need to manya$$y import it as you had to do it prior to Entity Framework .-.


(. A'ter c$ickin* on IFinishA= it wi$$ add Schoo$.edm4 'i$e into your pro2ect.

Cpen E"# desi*ner .y dou.$e c$ickin* on Schoo$.edm4 that disp$ays a$$ the entities 'or se$ected ta.$es and re$ation .etween
them as .e$owB

So this way you can create simp$e E"# 'rom your e4istin* data.ase.

;ow $etAs see a$$ the .ui$din* .$ocks o' *enerated E"# DSchoo$.edm4E as shown in a.ove 'i*ure.

Entity-Ta1le (appin,:

Each entity in E"# is mapped with data.ase ta.$e. :ou can check entity9ta.$e mappin* .y ri*ht c$ick on any entity in the E"#
desi*ner 9H se$ect &a.$e #appin*. A$so= i' you chan*e any property name o' entity 'rom desi*ner then ta.$e mappin* wou$d
re'$ect that automatica$$y.


Conte6t 7 Entity Classes:

Every Entity "ata #ode$ *enerates one conte4t c$ass and mu$tip$e entity c$asses 'or each "5 ta.$e. E4pand Schoo$.edm4 and
see two important 'i$es= KE"# ;ameL.!onte4t.tt and KE"# ;ameL.ttB


Schoo$.!onte4t.ttB &his &4 temp$ate 'i$e *enerates conte4t c$ass whenever you chan*e Entity "ata #ode$ D.edm4 'i$eE. :ou can
see conte4t c$ass 'i$e .y e4pandin* Schoo$.!onte4t.tt. !onte4t c$ass resides in KE"# ;ameL.conte4t.cs 'i$e. "e'au$t conte4t
c$ass name is K"5 ;ameL M Entities e*. !onte4t c$ass name 'or our Schoo$"5 is Schoo$"5Entities. !onte4t c$ass is derived
'rom "5!onte4t c$ass in Entity Framework .-. 1rior to EF .-= it used to derive 'rom C.2ect!onte4t.


Schoo$.ttB Schoo$.tt is &4 temp$ate 'i$e that *enerates entity c$asses 'or each "5 ta.$es. Entity c$asses are 1C!C D1$ain C$d
!/0 C.2ectE c$asses that can .e pro4y c$asses Dwe wi$$ see $ater what is pro4y c$assesE.

E"# "esi*nerB E"# desi*ner represents your conceptua$ mode$. It consist Entities= associations F mu$tip$icity .etween the
entities. Initia$$y it wi$$ e4act$y $ook $ike your data.ase ta.$e structure .ut you can add or mer*e co$umns or remove co$umns
which are not re@uired .y your app$ication 'rom this desi*ner. Even you can add new o.2ect in this mode$ which can have
co$umns 'rom di''erent data.ase ta.$es 'rom conte4t menu as shown in a.ove 'i*ure. 0emem.er= whatever chan*es you do
here it shou$d .e mapped with stora*e mode$. So you have to .e care'u$ whi$e doin* any chan*es in the desi*ner.

:ou can open this E"# desi*ner in N#/ view where you can see a$$ the three part o' E"#9 !onceptua$ schema D!S"/E=
Stora*e schema DSS"/E and mappin* schema D#S/E= to*ether in N#/ view.

0i*ht c$ick on Schoo$.edm4 9H c$ick ICpen with..A= this wi$$ open popup. Se$ect IN#/ Dte4tE EditorA in the popup. 6isua$ Studio
cannot disp$ay the mode$ in "esi*n view and in N#/ at the same time= so you wi$$ see a messa*e askin* whether itAs CO to
c$ose the "esi*n view o' the mode$. !$ick :es. &his wi$$ open N#/ view. :ou can see 'o$$owin* N#/ view .y to**$in* a$$
out$inin*


:ou can see SS"/ content= !S"/ content and !9S mappin* content here. I' you e4pand SS"/ and !S"/= each one has some
common N#/ node under each schema node. :ou donAt need to edit 4m$ .ecause you can do it in the #ode$ 5rowser.

#ode$ 5rowserB Cpen #ode$ 5rowser .y ri*ht c$ickin* on the E"# "esi*ner and se$ect #ode$ 5rowser 'rom conte4t menuB

#ode$ .rowser contains a$$ the in'ormation a.out the E"#= its conceptua$ mode$= stora*e mode$ and mappin* in'ormation.


Entity!ontainer Entity!ontainer is a wrapper 'or EntitySets and AssociationSets. It is critica$ entry point 'or @ueryin* the mode$.

EntitySetB EntitySet is a container 'or Entity&ype. It is set o' same entitytype. :ou can think it $ike d. ta.$e.

Entity&ypeB Entity&ype is a datatype in the mode$. :ou can see each Entity&ype 'or your conceptua$ mode$ in N#/. I' you
e4pand Entity&ype node in N#/= you can see each properties and its type and other in'o.

AssociationSetB AssociationSet de'ines the re$ation .etween each EntitySet.
8. Types of Entity in Entity Framework:
&here was 'our types o' Entities in Entity Framework 4.4=
1E EntityC.2ect
2E 1C!C
3E 1C!C 1ro4y Ddnamic pro4yE
4E Se$'9&rackin* Entities.

Entity Framework .- is $imited to 1C!C entity and "ynamic pro4y entity. EntityC.2ect used to use with C.2ect!onte4t which is
not .ein* used in Entity Framework .-. A$so= it is not recommended to use se$'9trackin* entities.

0C0 )lain 0ld C-9 012ect*: 1C!C c$ass is the c$ass that doesnAt depends on any 'ramework speci'ic .ase c$ass. It is $ike
any other norma$ .net c$ass that is why it is ca$$ed P1$ain C$d !/0 C.2ectsQ.

&hese 1C!C entities Da$so known as persistence9i*norant o.2ectsE support most o' the same @uery= insert= update= and de$ete
.ehaviors as entity types that are *enerated .y the Entity "ata #ode$. E*. Fo$$owin* is a Student 1C!C c$ass.

public class Student
{
public int StudentID { get; set; }
public string StudentName{ get; set; }
public Standard Standard{ get ; set; }
public StudentAddress StudentAddress{ get ; set; }
public IList<Course> Courses{ get; set; }
}
'ynamic ro6y )0C0 ro6y*:

"ynamic 1ro4y is a runtime pro4y c$ass o' 1C!C entity. 1C!C entity .ecomes 1C!C 1ro4y entity i' it meets the certain
re@uirements to ena.$e la:y loadin, and automatic chan,e trackin,. It adds some methods at runtime to your 1C!C c$ass
which does instant chan*e trackin* and $a3y $oadin* stu''.

1C!C entity shou$d meet the 'o$$owin* re@uirement to .ecome 1C!C pro4yB
1. A custom data c$ass must .e dec$ared with pu.$ic access.
2. A custom data c$ass must not .e sea$ed D;otInherita.$e in 6isua$ 5asicE
3. A custom data c$ass must not .e a.stract D#ustInherit in 6isua$ 5asicE.
4. 1ro4y!reationEna.$ed option shou$d not set to 'a$se Dde'au$t is trueE in conte4t c$ass
5. Each navi*ation property must .e dec$ared as pu.$ic= virtua$

.ote: 5y de'au$t dynamic pro4y is ena.$ed 'or every entity. <owever= you can disa.$e dynamic pro4y .y settin*
1ro4y!reationEna.$ed option to 'a$se in conte4t c$ass.
context.Configuration.ProxyCreationEnabled = false;

E"# *enerates 1C!C entities which satis'y a.ove re@uirement o' dynamic pro4y .y de'au$t.

Fo$$owin* is Student 1C!C c$ass *enerated .y E"#B

public partial class Student
{
public Student()
{
tis!Courses " ne# $asSet<Course>();
}

public int StudentID { get; set; }
public string StudentName { get; set; }
public Nullable<int> StandardId { get; set; }

public Standard Standard { get; set; }
public StudentAddress StudentAddress { get; set; }
public %irtual ICollection<Course> Courses { get; set; }
}
At runtime type o' Student wi$$ .e System."ata.Entity."ynamic1ro4ies.Student as .e$owB


7ettin* the actua$ entity type 'rom a dynamic pro4yB

:ou can use C.2ect!onte4t.7etC.2ect&ypeDE to 'ind actua$ type o' dynamic pro4y as .e$owB


Entity can have two types o' properties= Sca$ar properties and ;avi*ation properties.

+calar properties are properties whose actua$ va$ues are contained in the entity. For e4amp$e= Student entity has sca$ar
properties e.*. StudentId= Student;ame. &hese corresponds with the Student ta.$e co$umns.

.avi,ation properties are pointers to other re$ated entities. &he Student has Standard property as navi*ation property that wi$$
ena.$e app$ication to navi*ate 'rom a Student to re$ated Standard entity.
(. /ueryin, with E'(:
:ou can @uery E"# main$y .y three ways= 1E /I;) to Entities 2E Entity S)/ 3E ;ative S)/

1E /I;) to EntitiesB /2E @uery synta4 is easier to $earn than Entity S)/. :ou can use your /I;) ski$$s 'or @ueryin* with E"#.
&here are two types o' synta4 you can use with /I;)9to9Entities= /I;) #ethod Synta4 with /amda e4pression and /I;) @uery
synta4.

/I;) #ethod synta4D$amda e4pressionEB

&&'uer(ing #it LIN' to )ntities
using (%ar conte*t " ne# ScoolD+)ntities())
{
%ar L,)'uer( " conte*t!Students!#ere(s "> s!StudentName "" -+ill.);
}

/I;) )uery synta4B

using (%ar conte*t " ne# ScoolD+)ntities())
{
%ar L,)'uer( " /rom st in conte*t!Students
#ere st!StudentName "" 0+ill0
select st;
}
First= you have to create o.2ect o' conte4t c$ass which is Schoo$"5Entities. :ou shou$d initia$i3e it in usin*DE so that once it
*oin* out o' usin* scope then it wi$$ automatica$$y ca$$ "isposeDE method o' ".!onte4t. In .oth the synta4 a.ove= conte4t
returns I)uerya.$e.

We wi$$ $earn di''erent types o' /I;) to Entities @uery in pro2ection @uery chapter $ater.

2E Entity S)/B Entity S)/ is another way to create a @uery. It is processed .y the Entity FrameworkAs C.2ect Services direct$y. It
returns C.2ect)uery instead o' I)uerya.$e.

:ou need C.2ect!onte4t to create @uery usin* Entity S)/.

Fo$$owin* code snippet shows same @uery resu$t as /2E @uery a.ove.
&&'uer(ing #it 1b2ect Ser%ices and )ntit( S'L
string s3lString " 0S)L)C4 5AL6) st 7819 ScoolD+)ntities!Students 0 :
0AS st ;$)8) st!StudentName "" <+ill<0;

%ar ob2ct* " (ct* as I1b2ectConte*tAdapter)!1b2ectConte*t;

1b2ect'uer(<Student> student " ob2ct*!Create'uer(<Student>(s3lString);
Student ne#Student " student!7irst<Student>();

:ou can a$so use Entity!onnection and Entity!ommand to e4ecute Entity S)/ as .e$owB
using (%ar con " ne# )ntit(Connection(0name"ScoolD+)ntities0))
{
con!1pen();
)ntit(Command cmd " con!CreateCommand();
cmd!Command4e*t " 0S)L)C4 5AL6) st 7819 ScoolD+)ntities!Students as st #ere
st!StudentName"<+ill<0;
Dictionar(<int= string> dict " ne# Dictionar(<int= string>();
using ()ntit(Data8eader rdr " cmd!)*ecute8eader(Command+ea%ior!Se3uentialAccess >
Command+ea%ior!CloseConnection))
{
#ile (rdr!8ead())
{
int a " rdr!?etInt@,(A);
%ar b " rdr!?etString(B);
dict!Add(a= b);
}
}
}
Entity"ata0eader doesnAt return C.2ect)uery. It returns data in rows F co$umns.

6isit #S"; .$o* to $earn Entity S)/.

3E ;ative S)/ :ou can e4ecute native S)/ @uery 'or re$ationa$ data.ase as .e$owB

using (%ar ct* " ne# ScoolD+)ntities())
{
%ar studentName " ct*!Students!S3l'uer((0Select studentid= studentname= standardId /rom
Student #ere studentname"<+ill<0)!7irst1rDe/ault<Student>();
}
We wi$$ $earn to e4ecute raw s@$ @uery usin* ".!onte4t $ater.
;. Code First development with Entity Framework 3.1
6isua$ Studio 2-1- .rou*ht new approaches to mode$in* 'or Entity Framework 4.1.
1. !ode First
2. #ode$ First
3. "ata.ase 'irst
Code First: In the !ode First approach= you avoid workin* with visua$ mode$ desi*ner DE"#NE comp$ete$y. :ou write your
1C!C c$asses 'irst and then create data.ase 'rom these 1C!C c$asses. "eve$opers who 'o$$ow the path o' "omain9"riven
"esi*n D"""E princip$es pre'er to .e*in .y codin* their c$asses 'irst and then *eneratin* the data.ase re@uired to persist their
data.

1$ease visit EF Code-First Tutorial to $earn code 'irst in detai$.
<. (odel First development with Entity Framework
#ode$ FirstB In #ode$ First approach= you create Entities= re$ationships= and inheritance hierarchies direct$y on the desi*n
sur'ace o' E"#N. So in #ode$ First approach= when you add A"C.;E& Entity "ata #ode$= you shou$d se$ect Empty EF
'esi,ner model.


:ou can create entity= association and inheritance on empty desi*ner usin* too$.o4.


A'ter creatin* re@uired entities= associations and inheritance on desi*n sur'ace o' the empty mode$= you can use desi*nerAs
conte4t menu option J7enerate data.ase 'rom mode$J to *enerate ""/ script.


Se$ect e4istin* data.ase connection 'rom wi3ard and then it wi$$ disp$ay ""/ 'or the entities.


So this is ca$$ed #ode$ First approach.

15. 'ata1ase First development with Entity Framework 3.5
We have a$ready seen this approach in !reate Entity "ata #ode$ where we created mode$ and c$asses 'rom e4istin* data.ase.
So when you *enerate E"#N 'rom e4istin* data.ase then it is a "ata.ase First approach.
11. Entity -ifecycle:
5e'ore we work on !08" operation D!reate= 0ead= 8pdate= "e$eteE= itAs important to understand entity $i'ecyc$e and how itAs
.ein* mana*ed .y EntityFramework.

"urin* entityAs $i'etime= each entity has an entity state .ased on operation per'ormed on it via conte4t D".!onte4tE. &he entity
state is an enum o' type System.Data.EntityState that dec$ares the 'o$$owin* va$uesB
1. Added
2. "e$eted
3. #odi'ied
4. 8nchan*ed
5. "etached
&he !onte4t not on$y ho$ds the re'erence to a$$ the o.2ects retrieved 'rom the data.ase .ut a$so it ho$ds the entity states and
maintains modi'ications to the properties o' the entity. &his 'eature is known as Change Tracking.

&he chan*e in entity state 'rom the 8nchan*ed to the #odi'ied state is the on$y state thatAs automatica$$y hand$ed .y the
conte4t. A$$ other chan*es must .e made e4p$icit$y usin* proper methods o' ".!onte4t and ".Set. We wi$$ ses it $ater.
1#. Entity 9elationships:
:ou can have three types o' re$ations in E"# as in data.ase. 1E Cne to Cne 2E Cne to #any 3E #any to #any.

/etAs e4amine data.ase ta.$e desi*n .e'ore *oin* into re$ationships in E"#. Fo$$owin* 'i*ure is a data.ase dia*ram o'
Schoo$"5 used in this tutoria$.


As you can see in the 'i*ure= student and StudentAddress have Cne9to9Cne re$ationshionship where each student has 3ero or
one address.

Standard and &eacher has Cne9to9#any re$ationship where one standard can have many teacher .ut one teacher canAt *o to
many standard.

Student and !ourse has #any9to9#any re$ationships .y usin* Student!ourse ta.$e. Student!ourse consists primary key o'
.oth the ta.$es and thus it makes re$ation #any9to9#any.

When you create A"C.;E& Entity "ata #ode$ 'rom Schoo$"5 data.ase usin* EF 'esi,ner from data1ase option= it wi$$
create 'o$$owin* entities and re$ationships into E"#B

As you can see in the a.ove 'i*ure= Student and StudentAddress have Cne to Cne re$ationship D3ero or oneE. StudentAddress
entity has StudentId property as 1O which makes it Cne9to9Cne re$ationship.

Standard and teach have Cne9to9#any re$ation marked .y mu$tip$icity where 1 is 'or Cne and R is 'or many. Standard entity has
navi*ation property P&eachersQ which indicates that one Standard can have co$$ection o' teachers and &eacher entity has
PStandardQ navi*ation property which indicates that &eacher is associated with one Standard. &his makes it Cne9to9#any
re$ationship.

Student and !ourse have #any9to9#any re$ationships marked .y R mu$tip$icity= .ut it doesnAt disp$ay entityset 'or midd$e
ta.$e+tudentCourse where primary key o' .oth ta.$es wi$$ .e stored. &his is .ecause &he E"# represents many9to9many
re$ationships .y not havin* entityset 'or the 2oinin* ta.$e in !S"/= instead it mana*e throu*h mappin*. It can do this on$y when
the 2oinin* ta.$e doesnAt have any co$umns otherthan 1Os o' .oth the ta.$e. I' the 2oin ta.$es had additiona$ co$umns= such as
"ate!reated then the E"# wou$d have created entities 'or them and you have to mana*e #any9to9#any re$ationship entities
manua$$y.

(any-to-(any relationship in E'(:
Cpen E"# in N#/ view. :ou can see that SS"/ has Student!ourse entityset .ut !S"/ doesnAt have Student!ourse entityset
instead itAs .ein* mapped in navi*ation property o' Student and !ourse entity. In #S/ D!9S #appin*E= it has a mappin*
.etween Student and !ourse into Student!ourse ta.$e in SAssociationSet#appin*?H


&hus #any9to9#any re$ationship is .ein* mana*ed in !9S mappin* in E"#. So when you add student in course or !ourse in
Student entity and when you save it then it wi$$ insert 1O o' added student and course in Student!ourse ta.$e. So this mappin*
not on$y ena.$es a convenient association direct$y .etween the two entities= .ut a$so mana*es @ueryin*= inserts= and updates
across this 2oin.

.ote: E"# does this on$y when 2oinin* ta.$e has 1O co$umns 'or .oth ta.$es. I' you have some other co$umns in 2oinin* ta.$e
then E"# wi$$ treat as norma$ entity and you have to use IToinA in your @uery to 'etch the data.

Entity /raph0
When an entity has re$ation with other entities then 'u$$ o.2ect hierarchy is ca$$ed Ientity *raphA 'or e4amp$e 'o$$owin* is a
Student entity *raph that inc$udes its 'u$$ hierarchy o.2ect Standard= StudentAddress F !ourse.

1&. ro2ection /uery:
We wi$$ $earn some important 'eatures o' /I;)9to9Entities $ike 1ro2ection= /a3y $oadin* F Ea*er $oadin*. Onow$ed*e o' /I;) is
pre9re@uisites here.

1rojection0
1ro2ection is a process o' se$ectin* data in di''erent shape rather than speci'ic entity .ein* @ueried. &here are many ways o'
pro2ection. /etAs see some pro2ection sty$eB

First=First0r'efault:

I' you want to *et the sin*$e student o.2ect when there are many students whose name is UStudent1U in the data.ase then use
First or FirstCr"e'au$tB

%ar student " (/rom s in ct*!Students
#ere s!StudentName "" 0StudentB0
select s)!7irst1rDe/ault<Student>();

A.ove @uery wi$$ resu$t in 'o$$owin* data.ase @ueryB
S)L)C4 41C (B)
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DStudentNameE AS DStudentNameE=
D)*tentBE!DStandardIdE AS DStandardIdE
7819 DdboE!DStudentE AS D)*tentBE
;$)8) <StudentB< " D)*tentBE!DStudentNameE
"i''erence .etween First and FirstCr"e'au$t is that FirstDE wi$$ throw an e4ception i' there is no resu$t data 'or supp$ied criteria
where as FirstCr"e'au$tDE returns de'au$t va$ue Dnu$$E i' there is no resu$t data.

+in,le=+in,le0r'efault:

:ou can a$so use Sin*$e or Sin*$eCr"e'au$t to *et sin*$e student o.2ect as .e$owB

%ar student " (/rom s in conte*t!Students
#ere s!StudentID "" B
select s)!Single1rDe/ault<Student>();
A.ove /2E wou$d e4ecute 'o$$owin* data.ase @ueryB

S)L)C4 41C (,)
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DStudentNameE AS DStudentNameE=
D)*tentBE!DStandardIdE AS DStandardIdE
7819 DdboE!DStudentE AS D)*tentBE
;$)8) B " D)*tentBE!DStudentIDE
go
Sin*$e or Sin*$eCr"e'au$t wi$$ thrown an e4ception i' resu$t contains more than one e$ement. 8se Sin*$e or Sin*$eCr"e'au$t
where you are sure that resu$t wou$d contain on$y one e$ement= i' resu$t has mu$tip$e e$ement then there must .e some pro.$e.

To-ist:

I' you want to $ist o' a$$ students whose name is JStudent1J Dprovided there are many students has same nameE then use
&o/istDEB

%ar studentList " (/rom s in ct*!Students
#ere s!StudentName "" 0StudentB0
select s)!4oList<Student>();

A.ove /2E wou$d resu$t in 'o$$owin* data.ase @ueryB

S)L)C4
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DStudentNameE AS DStudentNameE=
D)*tentBE!DStandardIdE AS DStandardIdE
7819 DdboE!DStudentE AS D)*tentBE
;$)8) <StudentB< " D)*tentBE!DStudentNameE
go
>roupBy:

I' you want to *roup students .y standardId then use *roupB

%ar students " /rom s in ct*!Students
groupb( s!StandardId into students+(Standard
select students+(Standard;

A.ove /2E wou$d e4ecute 'o$$owin* data.ase @ueryB

S)L)C4
DCro2ect,E!DCBE AS DCBE=
DCro2ect,E!DStandardIdE AS DStandardIdE=
DCro2ect,E!DC,E AS DC,E=
DCro2ect,E!DStudentIDE AS DStudentIDE=
DCro2ect,E!DStudentNameE AS DStudentNameE=
DCro2ect,E!DStandardIdBE AS DStandardIdBE
7819 ( S)L)C4
DDistinctBE!DStandardIdE AS DStandardIdE=
B AS DCBE=
D)*tent,E!DStudentIDE AS DStudentIDE=
D)*tent,E!DStudentNameE AS DStudentNameE=
D)*tent,E!DStandardIdE AS DStandardIdBE=
CAS) ;$)N (D)*tent,E!DStudentIDE IS N6LL) 4$)N CAS4(N6LL AS int) )LS) B )ND AS DC,E
7819 (S)L)C4 DIS4INC4
D)*tentBE!DStandardIdE AS DStandardIdE
7819 DdboE!DStudentE AS D)*tentBE ) AS DDistinctBE
L)74 164)8 F1IN DdboE!DStudentE AS D)*tent,E 1N (DDistinctBE!DStandardIdE " D)*tent,E!
DStandardIdE) 18 ((DDistinctBE!DStandardIdE IS N6LL) AND (D)*tent,E!DStandardIdE IS N6LL))
) AS DCro2ect,E
18D)8 +G DCro2ect,E!DStandardIdE ASC= DCro2ect,E!DC,E ASC
go
0rderBy:

I' you want to *et the $ist o' students sorted .y Student;ame then use Crder5yB

%ar studentB " /rom s in ct*!Students
orderb( s!StudentName ascending
select s;

"ata.ase @ueryB
S)L)C4
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DStudentNameE AS DStudentNameE=
D)*tentBE!DStandardIdE AS DStandardIdE
7819 DdboE!DStudentE AS D)*tentBE
18D)8 +G D)*tentBE!DStudentNameE ASC
go
"nonymous Class result:
I' you want to *et on$y Student;ame= Standard;ame and $ist o' !ourses 'or that student in sin*$e o.2ect then write 'o$$owin*
pro2ectionB

%ar pro2ection8esult " /rom s in ct*!Students
#ere s!StudentName "" 0StudentB0
select ne# {
s!StudentName= s!Standard!StandardName= s!Courses
};

A.ove /2E wi$$ e4ecute 'o$$owin* data.ase @ueryB

S)L)C4
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DStudentNameE AS DStudentNameE=
D)*tent,E!DCit(E AS DCit(E
7819 DdboE!DStudentE AS D)*tentBE
L)74 164)8 F1IN DdboE!DStudentAddressE AS D)*tent,E 1N D)*tentBE!DStudentIDE " D)*tent,E!
DStudentIDE
;$)8) B " D)*tentBE!DStandardIdE
go
&ype o' pro2ection0esu$t in a.ove @uery wi$$ .e anonymous type .ecause there is no c$ass?entity which has these properties.
So compi$er wi$$ mark it as anonymous.

.ested !ueries:
:ou can a$so e4ecute nested /I;) to entities @ueries as .e$owB

A.ove nested @uery wi$$ resu$t in anonymous $ist with Student;ame and !ourse o.2ect.

S)L)C4
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DStudentNameE AS DStudentNameE=
DFoinBE!DCourseIdBE AS DCourseIdE=
DFoinBE!DCourseNameE AS DCourseNameE=
DFoinBE!DLocationE AS DLocationE=
DFoinBE!D4eacerIdE AS D4eacerIdE
7819 DdboE!DStudentE AS D)*tentBE
INN)8 F1IN (S)L)C4 D)*tent,E!DStudentIdE AS DStudentIdE= D)*tent@E!DCourseIdE AS DCourseIdBE=
D)*tent@E!DCourseNameE AS DCourseNameE= D)*tent@E!DLocationE AS DLocationE= D)*tent@E!D4eacerIdE AS
D4eacerIdE
7819 DdboE!DStudentCourseE AS D)*tent,E
INN)8 F1IN DdboE!DCourseE AS D)*tent@E 1N D)*tent@E!DCourseIdE " D)*tent,E!DCourseIdE ) AS
DFoinBE 1N D)*tentBE!DStudentIDE " DFoinBE!DStudentIdE
;$)8) B " D)*tentBE!DStandardIdE
go
So this way you can do pro2ection o' resu$t the way you want data. &here are di''erent other ways o' pro2ection .ut a$$ pro2ection
sty$es re@uires know$ed*e o' /I;).
13. Ea,er -oadin,:
Ea*er $oadin* is the process where.y a @uery 'or one type o' entity a$so $oads re$ated entities as part o' the @uery. Ea*er
$oadin* is achieved usin* Include method o' I)uerya.$e.

5e$ow code snippet shows ea*er $oadin* where Standard entity wi$$ a$so .e $oaded with Student entity usin* Inc$ude methodB

-I./ /uery +ynta6:

using (%ar conte*t " ne# ScoolD+)ntities())
{
%ar res " (/rom s in conte*t!Students!Include(0Standard0)
#ere s!StudentName "" 0StudentB0
select s)!7irst1rDe/ault<Student>();
}

-I./ (ethod +ynta6:

using (%ar ct* " ne# ScoolD+)ntities())
{
stud " ct*!Students!Include(s "> s!Standard)
!;ere(s "> s!StudentName "" 0StudentB0)!7irst1rDe/ault<Student>();

&&(ou can also pass entit( name as a string 0Standard0
&& stud " ct*!Students!Include(0Standard0)
!;ere(s "> s!StudentName "" 0StudentB0)!7irst1rDe/ault<Student>();
}

A.ove code wi$$ resu$t in 'o$$owin* S)/ @ueryB

S)L)C4 41C (B)
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DStudentNameE AS DStudentNameE=
D)*tent,E!DStandardIdE AS DStandardIdE=
D)*tent,E!DStandardNameE AS DStandardNameE=
D)*tent,E!DDescriptionE AS DDescriptionE
7819 DdboE!DStudentE AS D)*tentBE
L)74 164)8 F1IN DdboE!DStandardE AS D)*tent,E 1N D)*tentBE!DStandardIdE " D)*tent,E!DStandardIdE
;$)8) <StudentB< " D)*tentBE!DStudentNameE

-oad multiple levels of related entities:

:ou can a$so ea*er$y $oad mu$tip$e $eve$s o' re$ated entities. 5e$ow code snippet $oads re$ated Student= Standard and &eachersB

using (%ar ct* " ne# ScoolD+)ntities())
{
stud " ct*!Students!;ere(s "> s!StudentName "" 0StudentB0)
!Include(s "> s!Standard!4eacers)!7irst1rDe/ault<Student>();
}

A.ove code resu$ts in 'o$$owin* S)/ @ueryB

S)L)C4 DCro2ect,E!DStudentIDE AS DStudentIDE=
DCro2ect,E!DStudentNameE AS DStudentNameE=
DCro2ect,E!DStandardIdE AS DStandardIdE=
DCro2ect,E!DStandardNameE AS DStandardNameE=
DCro2ect,E!DDescriptionE AS DDescriptionE=
DCro2ect,E!DCBE AS DCBE=
DCro2ect,E!D4eacerIdE AS D4eacerIdE=
DCro2ect,E!D4eacerNameE AS D4eacerNameE=
DCro2ect,E!DStandardIdBE AS DStandardIdBE
7819 ( S)L)C4
DLimitBE!DStudentIDE AS DStudentIDE=
DLimitBE!DStudentNameE AS DStudentNameE=
DLimitBE!DStandardIdBE AS DStandardIdE=
DLimitBE!DStandardNameE AS DStandardNameE=
DLimitBE!DDescriptionE AS DDescriptionE=
DCro2ectBE!D4eacerIdE AS D4eacerIdE=
DCro2ectBE!D4eacerNameE AS D4eacerNameE=
DCro2ectBE!DStandardIdE AS DStandardIdBE=
CAS) ;$)N (DCro2ectBE!D4eacerIdE IS N6LL) 4$)N CAS4(N6LL AS int) )LS) B )ND AS DCBE
7819 (S)L)C4 41C (B) D)*tentBE!DStudentIDE AS DStudentIDE= D)*tentBE!DStudentNameE AS
DStudentNameE= D)*tentBE!DStandardIdE AS DStandardId,E= D)*tent,E!DStandardIdE AS DStandardIdBE=
D)*tent,E!DStandardNameE AS DStandardNameE= D)*tent,E!DDescriptionE AS DDescriptionE
7819 DdboE!DStudentE AS D)*tentBE
L)74 164)8 F1IN DdboE!DStandardE AS D)*tent,E 1N D)*tentBE!DStandardIdE " D)*tent,E!
DStandardIdE
;$)8) <updated student< " D)*tentBE!DStudentNameE ) AS DLimitBE
L)74 164)8 F1IN (S)L)C4
D)*tent@E!D4eacerIdE AS D4eacerIdE=
D)*tent@E!D4eacerNameE AS D4eacerNameE=
D)*tent@E!DStandardIdE AS DStandardIdE
7819 DdboE!D4eacerE AS D)*tent@E
;$)8) D)*tent@E!DStandardIdE IS N14 N6LL ) AS DCro2ectBE 1N DLimitBE!DStandardId,E "
DCro2ectBE!DStandardIdE
) AS DCro2ect,E
18D)8 +G DCro2ect,E!DStudentIDE ASC= DCro2ect,E!DStandardIdE ASC= DCro2ect,E!DCBE ASC


14. -a:y -oadin,:
Cne o' the important 'unctiona$ity o' Entity Framework is $a3y $oadin*. /a3y $oadin* means de$ayin* the $oadin* o' re$ated data
unti$ you speci'ica$$y re@uest it. For e4amp$e= Student c$ass contains StudentAddress as comp$e4 property. So conte4t 'irst
$oads a$$ the students 'rom the data.ase then it wi$$ $oad address o' particu$ar student when we access StudentAddress
property as .e$ow.

using (%ar ct* " ne# ScoolD+)ntities())
{
ct*!Con/iguration!LaH(Loading)nabled " true;
&&Loading students onl(
IList<Student> studList " ct*!Students!4oList<Student>();
Student std " studListDAE;
&&Loads Student address /or particular Student onl( (seperate S'L 3uer()
StudentAddress add " std!StudentAddress;
}

A.ove code wi$$ resu$t in two S)/ @uery. First= it wi$$ 'etch a$$ studentsB

S)L)C4
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DStudentNameE AS DStudentNameE=
D)*tentBE!DStandardIdE AS DStandardIdE
7819 DdboE!DStudentE AS D)*tentBE

And then sends 'o$$owin* @uery when we *et the re'erence o' StudentAddressB

e*ec spIe*ecutes3l N<S)L)C4
D)*tentBE!DStudentIDE AS DStudentIDE=
D)*tentBE!DAddressBE AS DAddressBE=
D)*tentBE!DAddress,E AS DAddress,E=
D)*tentBE!DCit(E AS DCit(E=
D)*tentBE!DStateE AS DStateE
7819 DdboE!DStudentAddressE AS D)*tentBE
;$)8) D)*tentBE!DStudentIDE " J)ntit(Ke(5alueB<=N<J)ntit(Ke(5alueB int<=J)ntit(Ke(5alueB"B

<owever= you can a$so turn o'' $a3y $oadin* 'or particu$ar property or entire conte4t. &o turn o'' $a3y $oadin* 'or particu$ar
property= do not make it virtua$. &o turn o'' $a3y $oadin* 'or a$$ entities in the conte4t= set its con'i*uration property to 'a$seB

public ScoolD+)ntities()L base(0name"ScoolD+)ntities0)
{
tis!Con/iguration!LaH(Loading)nabled " /alse;
}


9ules for la:y loadin,:
1. context.Configuration.ProxyCreationEnabled shou$d .e true.
2. context.Configuration.LayLoadingEnabled shou$d .e true.
3. !omp$e4 property shou$d .e de'ined as virtua$. !onte4t wi$$ not do $a3y $oadin* i' the property is not de'ine as virtua$.
18. E6plicit -oadin, with 'BConte6t
Even with $a3y $oadin* disa.$ed it is sti$$ possi.$e to $a3i$y $oad re$ated entities= .ut it must .e done with an e4p$icit ca$$. 8se
/oad method o' "5EntityEntry o.2ect.

Fo$$owin* code e4p$icit$y $oads Standard o' particu$ar Student usin* 0e'erenceDE method o' ".EntityEntryB

using (%ar conte*t " ne# ScoolD+)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<Student>();
conte*t!)ntr((student)!8e/erence(s "> s!Courses)!Load();
}
I' you run a.ove code= you can see that 'irst it $oads student .ut not standard as .e$owB


/oad method *et Standard entity as .e$owB


A.ove code e4ecute two di''erent data.ase @ueries. First @uery is to *et Student and second @uery to *et standard.

-oad collection:

8se co$$ection method instead o' 0e'erence method to $oad co$$ection navi*ation property. Fo$$owin* e4amp$e $oads courses o'
student.

using (%ar conte*t " ne# ScoolD+)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<Student>();
conte*t!)ntr((student)!Collection(s "> s!Courses)!Load();
}

;oteB &he /oad e4tension method works 2ust $ike &o/ist e4cept that it avoids the creation o' the $ist a$to*ether.
1?. 'BConte6t:
As you have seen in previous chapter= E"# *enerates !onte4t c$ass and Entity c$asses. &his conte4t c$ass is derived
'romSystem.Data.Entity.DbContext c$ass.

".!onte4t is a primary c$ass that is responsi.$e 'or interactin* with data as o.2ect. It o'ten re'erred to as conte4t. It does
'o$$owin* activitiesB
/ueryin,: It can .e use'u$ in @ueryin* the data.ase. It converts data.ase va$ues into entity o.2ects and vica versa.
Chan,e Trackin,: It keeps track o' chan*es occurred in the entities a'ter it has .een @ueryin* 'rom the data.ase.
ersistin, 'ata: It a$so per'orm Insert= update and de$ete operation to the data.ase .ased on the entity states.

1rior to EntityFramework 4.1= E"# used to *enerate conte4t c$ass that derived 'rom C.2ect!onte4t c$ass. It was $itt$e tricky to
work with C.2ect!onte4t. ".!onte4t is conceptua$$y simi$ar to C.2ect!onte4t. It is a wrapper around C.2ect!onte4t which is
use'u$ in a$$ deve$opment mode$sB !ode First= #ode$ First and "ata.ase First.

"5!onte4t A1I is easier to use than C.2ect!onte4t A1I 'or a$$ common tasks. <owever= you can *et re'erence o' C.2ect!onte4t
'rom "5!onte4t to use some o' the 'eatures o' C.2ect!onte4t .y usin* IC.2ect!onte4tAdpter as .e$owB

using (%ar ct* " ne# ScoolD+)ntities())
{
%ar ob2ectConte*t " (ct* as I1b2ectConte*tAdapter)!1b2ectConte*t;
&&use ob2ectConte*t no#M
}

See what are the important methods and properties o' ".!onte4t c$ass in the ne4t chapter.

1;. 'BConte6t Class
"5!onte4t represents a com.ination o' the 8nit9C'9Work and 0epository patterns and ena.$es you to @uery a data.ase and
*roup to*ether chan*es that wi$$ then .e written .ack to the store as a unit.

Fo$$owin*s are important methods o' "5!onte4t c$ass.

1u.$ic #ethodsB
Method Name Return Type Description Example
Entry(Object) DBEntityEntryGets a DbEntityEntry object
for the given entity proviing
access to infor!ation abo"t
the entity an the abi#ity to
perfor! actions on the entity.
Entry !etho ret"rns DBEntityEntry object of passe entity object thro"gh
$hich $e can change its state% c"rrent&a#"es an origina#&a#"es.
b't(.Entry()t"entEntity).)tate * )yste!.Data.Entity)tate.+oifie,
b't(.Entry()t"entEntity).'"rrent&a#"es.)et&a#"es()t"entEntityD-O),
b't(.Entry()t"entEntity).Origina#&a#"es.)et&a#"es()t"entEntityD-O),
Entry
.-Entity/(-Entity)
DbEntityEntry
.-Entity/
Gets a
DbEntityEntry.-Entity/
object for the given entity
proviing access to
infor!ation abo"t the entity
an the abi#ity to perfor!
actions on the entity.
)a!e as Entry !etho b"t this generic !etho oes type chec0 of passe
EntityObject before ret"rning DBEntityEntry object
)et(-ype) DB)et 1et"rns a Db)et for the
specifie type% this a##o$s
'12D operations to be
perfor!e for the given
entity in the conte(t.
'12D operation.
ct(.)et(st".Get-ype().Base-ype).3(st"entEntity),
ct(.)et(st".Get-ype().Base-ype).3ttach(st"entEntity),
ct(.)et(st".Get-ype().Base-ype).1e!ove(st"entEntity),
var res"#t * ct(.)et(st"entEntity.Get-ype().Base-ype).)4#5"ery(6se#ect 7
fro! st"ent6),
st"entEntity.Get-ype() $i## ret"rn 8O'O 8ro(y type.
st"entEntity.Get-ype().Base-ype sho"# be "se to get an act"a# entity type.
)et.-Entity/() DB)et 1et"rns a Db)et for the
specifie type% this a##o$s
'12D operations to be
perfor!e for the given
entity in the conte(t.
'12D operation.
bconte(t.)et.)t"ent/().3(st"entEntity),
bconte(t.)et.)t"ent/().3ttach(st"entEntity),
bconte(t.)et.)t"ent/().1e!ove(st"entEntity),
var res"#t * bconte(t.)et().)4#5"ery(6se#ect 7 fro! st"ent6),
)ave'hanges() int )aves a## changes !ae in this
conte(t to the "ner#ying
atabase.
)ave changes to the atabase9
Dbconte(t.)ave'hanges(),
1rotected #ethodsB
Method Name Return Type Description
)ho"#&a#iateEntity boo# E(tension point a##o$ing the "ser to overrie the efa"#t behavior of va#iating on#y ae
an !oifie entities.
&a#iateEntity DbEntity&a#iation1es"#t E(tension point a##o$ing the "ser to c"sto!i:e va#iation of an entity or fi#ter o"t
va#iation res"#ts. 'a##e by Get&a#iationErrors().
1u.$ic 1ropertiesB
Property Name Return Type Description
'hange-rac0er DB'hange-rac0er 8rovies access to feat"res of the conte(t that ea# $ith change trac0ing of entities.
'onfig"ration DB'onte(t'onfig"ration 8rovies access to config"ration options for the conte(t.
Database Database 'reates a atabase instance for this conte(t an a##o$s yo" to perfor! creation% e#etion or
e(istence chec0s for the "ner#ying atabase.

6isit #S"; 'or more in'ormation o' "5!onte4t c$ass.
1<. 'B+et Class
"5Set c$ass represents an entity set that is use 'or create= read= update= and de$ete operations. A *eneric version o' "5Set
D".SetE can .e used when the type o' entity is not known at .ui$d time.

:ou can *et re'erence o' "5Set .y usin* "5!onte4t e*. d.conte4t.Students or d.conte4t.Standards or any entity set.
".!onte4t c$ass inc$udes ".Set as .e$owB

Some o' the important methods o' "5Set c$assB

Method Name Return Type Description Example
3 3e entity
type
3s the given entity to the
conte(t the 3e state.
;hen the changes are being
save% the entities in the
3e states are inserte
into the atabase. 3fter the
changes are save% the object
state changes to 2nchange.
bconte(t.)t"ents.3(st"entEntity)
3s<o-rac0ing.Entity/ DB5"ery.Entity/ 1et"rns a ne$ 4"ery $here
the entities ret"rne $i## not
be cache in the Db'onte(t.
(=nherite fro! Db5"ery.)
Entities ret"rne as
3s<o-rac0ing% $i## not be
trac0e by DB'onte(t. -his
$i## be significan
perfor!ance boost for rea
on#y entities.
var st"ent>ist *
bconte(t.)t"ents.3s<o-rac0ing.)t"ent/().-o>ist.)t"ent/(),
3ttach(Entity) Entity $hich $as
passe as
para!eter
3ttaches the given entity to
the conte(t in the 2nchange
state
bconte(t.)t"ents.3ttach(st"entEntity),
'reate Entity 'reates a ne$ instance of an
entity for the type of this set.
-his instance is not ae or
attache to the set. -he
instance ret"rne $i## be a
pro(y if the "ner#ying
conte(t is config"re to
create pro(ies an the entity
type !eets the re4"ire!ents
for creating a pro(y.
&ar ne$)t"entEntity * bconte(t.)t"ents.'reate(),
?in(int) Entity type 2ses the pri!ary 0ey va#"e to
atte!pt to fin an entity
trac0e by the conte(t. =f the
entity is not in the conte(t
then a 4"ery $i## be e(ec"te
an eva#"ate against the
ata in the ata so"rce% an
n"## is ret"rne if the entity is
not fo"n in the conte(t or in
the ata so"rce. <ote that
the ?in a#so ret"rns entities
that have been ae to the
@@?in st"ent $hose )t"ent=D is 1
)t"ent st"Entity * bconte(t.)t"ents.?in(1),
conte(t b"t have not yet
been save to the atabase.
=nc#"e DB5"ery 1et"rns the inc#"e non
generic >=<5 to Entities
4"ery against a Db'onte(t.
(=nherite fro! Db5"ery)
var st"ent>ist *
bconte(t.)t"ents.=nc#"e(6)t"ent3ress6).-o>ist.)t"ent/(),
var st"ent>ist * bconte(t.)t"ents.=nc#"e(s */
s.)t"ent3ress).-o>ist.)t"ent/(),
1e!ove 1e!ove entity +ar0s the given entity as
De#ete. ;hen the changes
are save% the entity is
e#ete fro! the atabase.
-he entity !"st e(ist in the
conte(t in so!e other state
before this !etho is ca##e.
bconte(t.)t"ents.1e!ove(st"entEntity),
)4#5"ery DB)4#5"ery 'reates a ra$ )5> 4"ery that
$i## ret"rn entities in this set.
By efa"#t% the entities
ret"rne are trac0e by the
conte(t, this can be change
by ca##ing 3s<o-rac0ing on
theDb)4#5"ery.-Entity/
ret"rne fro! this !etho.
var st"entEntity * bconte(t.)t"ents.)4#5"ery(6se#ect 7 fro!
st"ent $here st"enti * 16).?irstOrDefa"#t.)t"ent/()

6isit #S"; 'or more in'ormation o' "5Set c$ass.
#5. 'BEntityEntry Class
"5EntityEntry is an important c$ass which is use'u$ to *et various in'ormation a.out an entity. :ou can *et an instance o'
"5EntityEntry o' particu$ar entity .y usin* Entry method o' "5!onte4t. For e4amp$eB

"5EntityEntry studentEntry V d.conte4t.EntryDStudentEntityEW

"5EntityEntry c$ass has 'o$$owin* important methodsB

Method Name Return Type Description Example
'o##ection DB'o##ectionEntry Gets an object that represents
the co##ection navigation
property fro! this entity to a
co##ection of re#ate entities.
var st"entDBEntityEntry *
b'onte(t.Entry(st"entEntity),
var co##ection8roperty *
st"entDBEntityEntry.'o##ection(s */ s.'o"rses),
'o!p#e(8roperty DB'o!p#e(
8ropertyEntry
Gets an object that represents
a co!p#e( property of this
entity.
var st"entDBEntityEntry *
b'onte(t.Entry(st"entEntity),
var co!p#e(8roperty *
st"entDBEntityEntry.'o!p#e(8roperty
(st".)t"ent)tanar),
GetDatabase&a#"es DB8roperty&a#"es 5"eries the atabase for copies
of the va#"es of the trac0e
entity as they c"rrent#y e(ist in
the atabase. 'hanging the
va#"es in the ret"rne
ictionary $i## not "pate the
va#"es in the atabase. =f the
entity is not fo"n in the
atabase then n"## is ret"rne.
var st"entDBEntityEntry *
b'onte(t.Entry(st"entEntity),
var b8rop&a#"es *
st"entDBEntityEntry.GetDatabase&a#"es(),
8roperty DB8ropertyEntry Gets an object that represents
a sca#ar or co!p#e( property of
this entity.
var st"entDBEntityEntry *
b'onte(t.Entry(st"entEntity),
string property<a!e *
st"entDBEntityEntry.8roperty
(6)t"ent<a!e6).<a!e,
1eference DB1eferenceEntry Gets an object that represents
the reference (i.e. nonA
co##ection) navigation property
fro! this entity to another
entity.
var st"entDBEntityEntry *
b'onte(t.Entry(st"entEntity),
var reference8roperty *
st"entDBEntityEntry.1eference
(s */ s.)tanar),
1e#oa voi 1e#oas the entity fro! the
atabase over$riting any
property va#"es $ith va#"es
fro! the atabase. -he entity
$i## be in the 2nchange state
after ca##ing this !etho.
var st"entDBEntityEntry *
b'onte(t.Entry(st"entEntity),
st"entDBEntityEntry.1e#oa(),

6isit #S"; 'or more in'ormation o' "5EntityEntry c$ass.
#1. $orkin, with Entity roperty @alue
&he Entity Framework keeps track o' each properties va$ue o' a tracked entity. "51ropertyEntry a$$ow access to the state o' the
sca$ar or comp$e4 property $ike current va$ue= ori*ina$ va$ue etc. Fo$$owin*s are important properties o' "51ropertyEntry c$assB

Property Name Description
'"rrent&a#"e Gets or sets the c"rrent va#"e of this property. (Overries Db+e!berEntry.'"rrent&a#"e.)
EntityEntry -he DbEntityEntry to $hich this property be#ongs. (Overries Db+e!berEntry.EntityEntry.)
=s+oifie Gets or sets a va#"e inicating $hether the va#"e of this property has been !oifie since it $as #oae fro! the
atabase.
<a!e Gets the property na!e. (Overries Db+e!berEntry.<a!e.)
Origina#&a#"e Gets or sets the origina# va#"e of this property.
8arent8roperty -he Db8ropertyEntry of the property for $hich this is a neste property. -his !etho $i## on#y ret"rn a nonAn"## entry for
properties of co!p#e( objects% other$ise it $i## ret"rn n"## for properties of the entity itse#f.
5e$ow code snippet shows how to access property va$ueB

using (%ar ct* " ne# ScoolD+)ntities())
{
%ar stud " ct*!Students!Include(sadd "> sadd!StudentAddress)
!;ere(s "> s!StudentName "" 0StudentB0)!7irst1rDe/ault<Student>();
stud!StudentName " 0Canged Student Name0;

string propert(Name " ct*!)ntr((stud)!Cropert((0StudentName0)!Name;
string current5alue " ct*!)ntr((stud)!Cropert((0StudentName0)!Current5alue!4oString();
string original5alue " ct*!)ntr((stud)!Cropert((0StudentName0)!1riginal5alue!4oString();
bool isCanged " ct*!)ntr((stud)!Cropert((0StudentName0)!Is9odi/ied;
%ar db)ntit( " ct*!)ntr((stud)!Cropert((0StudentName0)!)ntit()ntr(;
}

6isit #S"; 'or more in'ormation.
##. -ocal 'ata
&he /oca$ property o' "5Set provides simp$e access to the entities that are current$y .ein* tracked .y the conte4t and have not
.een marked as "e$eted. /oca$ keeps track o' entities whose entity state is added= modi'ied and unchan*ed. For e4amp$eB

using (%ar ct* " ne# ScoolD+)ntities())
{
ct*!Students!Load();
ct*!Students!Add(ne# Student() { StudentName " 0Ne# StudentB0 });
ct*!Students!8emo%e(ct*!Students!7ind(,NA));


&& Loop o%er te unicorns in te conte*t!
Console!;riteLine(0In LocalL 0);
/oreac (%ar student in ct*!Students!Local)
{
Console!;riteLine(07ound {A}L {B} #it state {,}0=
student!StudentID= student!StudentName=
ct*!)ntr((student)!State);
}
&& Cer/orm a 3uer( against te database!
Console!;riteLine(0OnIn DbSet 3uer(L 0);
/oreac (%ar student in ct*!Students)
{
Console!;riteLine(07ound {A}L {B} #it state {,}0=
student!StudentID= student!StudentName=
ct*!)ntr((student)!State);
}
}

CutputB
In /oca$ B
Found -B ;ew Student1 with state Added
Found 2B Student2 with state 8nchan*ed
Found 3B Student3 with state 8nchan*ed

In ".Set @ueryB
Found 1B Student1 with state "e$eted
Found 2B Student2 with state 8nchan*ed
Found 3B Student3 with state 8nchan*ed

;oteB /oca$ is C.serva.$e!o$$ection so it is not advisa.$e use 'or *ood per'ormance i' you use it with "5Set which keeps track
o' thousands o' entities.

6isit #S"; 'or more in'ormation on /oca$.
#&. E6ecute .ative +/- /uery
:ou can e4ecute native raw S)/ @uery a*ainst data.ase usin* "5!onte4t.

:ou can write three types o' @ueriesB
1. S)/ @uery 'or entity types which return particu$ar types o' entities
2. S)/ @uery 'or non9entity types which returns primitive data type
3. 0aw S)/ commands to the data.ase
+/- !uery for entity types:
As we have seen in one o' the previous chapters that "5Set has S)/)uery method to write raw S)/ @uery which returns
entity instances. &he returned o.2ects wi$$ .e tracked .y the conte4t 2ust as they wou$d .e i' there were returned .y a /I;)
@uery. For e4amp$eB

using (%ar ct* " ne# ScoolD+)ntities())
{
%ar studentList " ct*!Students!S3l'uer((0Select P /rom Student0)!4oList<Student>();

}

<owever= co$umns returned .y S)/ @uery shou$d match property o' entity type o' "5Set otherwise it wi$$ throw an e4ception.
For e4amp$eB

using (%ar ct* " ne# ScoolD+)ntities())
{
%ar studentName " ct*!Students!S3l'uer((0Select studentid= studentname
/rom Student #ere studentname"<Ne# StudentB<0)!4oList();
}

I' you chan*e co$umn name in @uery then it wi$$ throw an e4ception .ecause it must match co$umn namesB

using (%ar ct* " ne# ScoolD+)ntities())
{
&&tis #ill tro# an e*ception
%ar studentName " ct*!Students!S3l'uer((0Select studentid as id= studentname as name
/rom Student #ere studentname"<Ne# StudentB<0)!4oList();
}

+/- !uery for non-entity types:
A S)/ @uery returnin* instances o' any type= inc$udin* primitive types= can .e created usin* the S@$)uery method on
the 'ata1ase class. For e4amp$eB

using (%ar ct* " ne# ScoolD+)ntities())
{
&&?et student name o/ string t(pe
string studentName " ct*!Database!S3l'uer(<string>(0Select studentname
/rom Student #ere studentid"B0)!7irst1rDe/ault<string>();
}

9aw +/- commands to the data1ase:
E4ecuteS@$!ommnad method is use'u$ to send non9@uery commands to the data.ase $ike Insert= 8pdate or "e$ete command.
For e4amp$eB

using (%ar ct* " ne# ScoolD+)ntities())
{
&&6pdate command
int no1/8o#6pdated " ct*!Database!)*ecuteS3lCommand(06pdate student
set studentname "<canged student b( command< #ere studentid"B0);
&&Insert command
int no1/8o#Inserted " ct*!Database!)*ecuteS3lCommand(0insert into
student(studentname)
%alues(<Ne# Student<)0);
&&Delete command
int no1/8o#Deleted " ct*!Database!)*ecuteS3lCommand(0delete /rom student
#ere studentid"B0);
}


#3. @alidate Entity
:ou can write custom server side va$idation 'or any entity. :ou need to override 6a$idateEntity method o' "5!onte4t. For
e4amp$eB

protected o%erride S(stem!Data!)ntit(!5alidation!Db)ntit(5alidation8esult
5alidate)ntit((Db)ntit()ntr( entit()ntr(= S(stem!Collections!?eneric!IDictionar(<ob2ect= ob2ect>
items)
{
i/ (entit()ntr(!)ntit( is Student)
{
i/ (entit()ntr(!Current5alues!?et5alue<string>(0StudentName0) "" 00)
{
%ar list " ne# List<S(stem!Data!)ntit(!5alidation!Db5alidation)rror>();
list!Add(ne# S(stem!Data!)ntit(!5alidation!Db5alidation)rror(0StudentName0=
0StudentName is re3uired0));
return ne# S(stem!Data!)ntit(!5alidation!Db)ntit(5alidation8esult(entit()ntr(=
list);
}
}
return base!5alidate)ntit((entit()ntr(= items);
}

As you can see in the a.ove code that we are va$idatin* Student entity. I' Student;ame is .$ank then we are addin*
"56a$idationError into "5Entity6a$idation0esu$t. So whenever you ca$$ "5!onte4t.Save!han*es method and i' you try to save
Student entity without Student;ame then it wi$$ throw ".Entity6a$idationE4ception. For e4amp$eB

tr(
{
using (%ar ct* " ne# ScoolD+)ntities())
{
ct*!Students!Add(ne# Student() { StudentName " 00 });
ct*!Standards!Add(ne# Standard() { StandardName " 00 });
ct*!Sa%eCanges();
}
}
catc (Db)ntit(5alidation)*ception db)*)
{
/oreac (Db)ntit(5alidation8esult entit()rr in db)*!)ntit(5alidation)rrors)
{
/oreac (Db5alidation)rror error in entit()rr!5alidation)rrors)
{
Console!;riteLine(0)rror Cropert( Name {A} L )rror 9essageL {B}0=
error!Cropert(Name= error!)rror9essage);
}
}
}


#4. ersistence in Entity Framework
/earn how to persist an entity so that it either inserts new row or updates an e4istin* row or de$ete an e4istin* row in the
data.ase.

We need to consider two scenarios= connected scenario and disconnected scenario.

!onnected ScenarioB !onnected scenario is when an entity is retrieved 'rom the data.ase and persist usin* same conte4t.
!onte4t o.2ect doesnAt destroy .etween when entity retriva$ and persistence.


"isconnected ScenarioB "isconnected scenario is when an entity is retrieved 'rom the data.ase and modi'ied usin* di''erent
conte4ts. "isconnected scenario is comp$e4 .ecause new conte4t doesnAt know anythin* a.out modi'ied entity so you have to
te$$ conte4t that what has chan*ed in entity. In the .e$ow 'i*ure= c$ient retrieve entity *raph usin* !onte4t 1 and then it per'orm
some !8" Dcreate= update= "e$eteE operations and then it saves entity *raph usin* !onte4t 2. !onte4t 2 doesnAt know which
operation has .een per'ormed on the entity *raph in this scenario.


C9A' 0peration in Connected +cenario:

!08" operation in connected scenario is 'air$y easy task .ecause conte4t automatica$$y detact chan*es happened in the entity
provided Auto"etect!han*esEna.$ed is true .y de'au$t.

Fo$$owin* e4amp$e show how you can add= update and de$ete entity usin* conte4t and ca$$ conte4t.Save!han*esDE method to
update the data.ase.

using (%ar conte*t " ne# ScoolD+)ntities())
{
%ar studentList " conte*t!Students!4oList<Student>();
&&Cer/orm create operation
conte*t!Students!Add(ne# Student() { StudentName " 0Ne# Student0 });
&&Cer/orm 6pdate operation
Student student4o6pdate " studentList!;ere(s "> s!StudentName ""
0studentB0)!7irst1rDe/ault<Student>();
student4o6pdate!StudentName " 0)dited studentB0;
&&Cer/orm delete operation
conte*t!Students!8emo%e(studentList!)lementAt<Student>(A));
&&)*ecute Inser= 6pdate Q Delete 3ueries in te database
conte*t!Sa%eCanges();
}

.ote: I' Auto"etect!han*esEna.$ed is set to 'a$se then conte4t cannot detect chan*es made to e4istin* entities so do not
e4ecute update @uery. :ou need to ca$$ conte4t.!han*e&racker."etect!han*esDE .e'ore Save!han*esDE in order to detect
edited entities and mark their status #odi'ied.

!onte4t detects addin* and de$etin* entity when per'ormed on$y on ".Set. I' you per'orm add and de$ete entity on separate
co$$ection or $ist then it wonAt detect these chan*es.

Fo$$owin* code wi$$ .0T insert or de$ete student. It wi$$ on$y do update studentB

using (%ar conte*t " ne# ScoolD+)ntities())
{
%ar studentList " conte*t!Students!4oList<Student>();
&&Add student in list
studentList!Add(ne# Student() { StudentName " 0Ne# Student0 });
&&Cer/orm update operation
Student student4o6pdate " studentList!;ere(s "> s!StudentName ""
0StudentB0)!7irst1rDe/ault<Student>();
student4o6pdate!StudentName " 0)dited studentB0;
&&Delete student /rom list
i/ (studentList!Count > A)
studentList!8emo%e(studentList!)lementAt<Student>(A));
&&Sa%eCanges #ill onl( do update operation not add and delete
conte*t!Sa%eCanges();
}

/earn how to do !08" operation in disconnected scenario in the ne4t chapters.
#8. "ttach Entity >raph in 'isconnected +cenario:
EntityFramework 4.3 and a.ove has 'o$$owin* important 'unctions that can .e use'u$ to attach an entity *raph to the ".!onte4t.

".Set.addDEB

".Set.addDE method adds a$$ the entities o' entity *raph to the conte4t and mark a$$ the entities as Added.


".Set.AttachDEB

".Set.attachDE method attaches who$e entity *raph to the conte4t with 8nchan*ed entity state.


".!onte4t.EntryDEB

DbContext.Entry!standardEntity"ra#h$.state = EntityState.%dded&'odified&Deleted&(nchanged. &his method attaches who$e
entity *raph to the conte4t with speci'ied state to parent entity and set other entities state as 8nchan*ed.


"own$oad samp$e pro2ect 'or the demo.
#?. "dd Entity usin, 'BConte6t
In this chapter we wi$$ $earn how to add and save sin*$e entity usin* ".!onte4t in disconnected scenario which in9tern insert
sin*$e row in data.ase ta.$e.

We wi$$ see how to add sin*$e JStandardJ entityB

&& 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# ScoolD+)ntities())
{
&&Add standard ob2ect into Standard D+set
dbCt*!Standards!Add(ne#Standard);
&& call Sa%eCanges metod to sa%e standard into database
dbCt*!Sa%eCanges();
}

As you can see in a.ove code snippet= 'irst we have created new Standard entity o.2ect and set Standard;ame to JStandard 1J.
Second= created new "5!onte4t o.2ect and added new$y created Standard entity into Standards EntitySet. &hird= ca$$in*
Save!han*es method o' "5!onte4t which sends insert @uery to the data.ase.

&his wi$$ resu$t in 'o$$owin* S)/ @uery to the data.aseB

e*ec spIe*ecutes3l N<insert DdboE!DStandardE(DStandardNameE= DDescriptionE)
%alues (JA= null)
select DStandardIdE
/rom DdboE!DStandardE
#ere JJ81;C16N4 > A and DStandardIdE " scopeIidentit(()<=N<JA %arcar(RA)<=JA"<Standard B<

A$ternative$y= we can a$so add Standard entity into "5!onte4t.Entry and mark it as Added which resu$t in same insert @ueryB
dbCt*!)ntr((ne#Standard)!State " S(stem!Data!)ntit(State!Added;

So this way you can add sin*$e entity.

In the ne4t chapter we wi$$ $earn how to add entities which has one9to9one re$ationship.
#;. Apdate Entity usin, 'BConte6t
As we have $earned a.out "5!onte4t.Entry method in previous chapter= Entry method is use'u$ to *et "5EntityEntry 'or *iven
Entity.

Fo$$owin* statement attach entity into conte4t and mark its state to #odi'iedB

d.!t4.EntryDEntityE.State V System."ata.EntityState.#odi'iedW

/etJs see how to update an e4istin* sin*$e JStandardJ entityB

Student stud ;
&& ?et student /rom D+
using (%ar ct* " ne# ScoolD+)ntities())
{
stud " ct*!Students!;ere(s "> s!StudentName "" 0Ne# StudentB0)!7irst1rDe/ault<Student>();
}
&& cange student name in disconnected mode (out o/ D+Conte*t scope)
i/ (stud S" null)
{
stud!StudentName " 06pdated StudentB0;
}
&&sa%e modi/ied entit( using ne# D+Conte*t
using (%ar dbCt* " ne# ScoolD+)ntities())
{
&&9arT entit( as modi/ied
dbCt*!)ntr((stud)!State " S(stem!Data!)ntit(State!9odi/ied;
dbCt*!Sa%eCanges();
}


As you see in the a.ove code snippet= we are doin* 'o$$owin* stepsB
1. 7et the e4istin* student
2. !han*e student name out o' "5!onte4t scope Ddisconnected modeE
3. We pass modi'ied entity into Entry method to *et its "5EntityEntry o.2ect and then markin* its state as #odi'ied
4. !a$$in* Save!han*es to update student in'ormation into the data.ase.
Save!han*es wi$$ send 'o$$owin* update @uery to the data.aseB

e*ec spIe*ecutes3l N<update DdboE!DStudentE
set DStudentNameE " JA= DStandardIdE " JB
#ere (DStudentIDE " J,)<=N<JA %arcar(RA)=
JB int=J, int<=JA"<6pdated StudentB<=JB",UU=J,",VN

So this way we can easi$y update an entity usin* "5!onte4t.

In the ne4t chapter we wi$$ $earn how to update an one9to9one re$ationship entities.

#<. 'elete Entity usin, 'BConte6t
We used EntryDE method o' ".!onte4t to mark EntityState to #odi'ied in the previous chapter. Same way we can use EntryDE
method to attach disconnected entity to the conte4t and mark its state to "e$eted.

using (%ar conte*t " ne# ScoolD+)ntities())
{
conte*t!)ntr((disconnected4eacer)!State " S(stem!Data!)ntit(State!Deleted;
conte*t!Sa%eCanges();
}

A.ove code resu$ts in 'o$$owin* de$ete @uery which de$etes the row 'rom &eacher ta.$e.
delete DdboE!D4eacerE
#ere (D4eacerIdE " JA)<=N<JA int<=JA"B

&5. "dd Entity >raph usin, '1Conte6t:
Addin* a$$ new entities in entity *raph is simp$e task. We can use ".Set.AddDE method to attach who$e entity *raph to the
conte4t and set a$$ the entityJs states to Added. E*. !$ient has created new Standard and &eacher entities that needs to .e
inserted in the data.ase.


Fo$$owin* e4amp$e add student entity *raph in disconnected mode usin* ".Set.AddDE method which marks added state to a$$
the entitiesB

&&Create student in disconnected mode
Student ne#Student " ne# Student() { StudentName " 0Ne# Single Student0 };

&&Assign ne# standard to student entit(
ne#Student!Standard " ne# Standard() { StandardName " 0Ne# Standard0 };

&&add ne# course #it ne# teacer into student!courses
ne#Student!Courses!Add(ne# Course() { CourseName " 0Ne# Course /or single student0= 4eacer "
ne# 4eacer() { 4eacerName " 0Ne# 4eacer0 } });
using (%ar conte*t " ne# ScoolD+)ntities())
{
conte*t!Students!Add(ne#Student);
conte*t!Sa%eCanges();
Console!;riteLine(0Ne# Student )ntit( as been added #it ne# StudentId" 0 :
ne#Student!StudentID!4oString());
Console!;riteLine(0Ne# Standard )ntit( as been added #it ne# StandardId" 0 :
ne#Student!StandardId!4oString());
Console!;riteLine(0Ne# Course )ntit( as been added #it ne# CourseId" 0 :
ne#Student!Courses!)lementAt(A)!CourseId!4oString());
Console!;riteLine(0Ne# 4eacer )ntit( as been added #it ne# 4eacerId" 0 :
ne#Student!Courses!)lementAt(A)!4eacerId!4oString());
}
0utput:
;ew Student Entity has .een added with new StudentIdV 14
;ew Standard Entity has .een added with new StandardIdV %
;ew !ourse Entity has .een added with new !ourseIdV (
;ew &eacher Entity has .een added with new &eacherIdV ,

&his e4ecutes 'o$$owin* ""/ statements to the data.aseB

e*ec spIe*ecutes3l N<INS)84 DdboE!DStandardE(DStandardNameE= DDescriptionE)
5AL6)S (JA= N6LL)
S)L)C4 DStandardIdE
7819 DdboE!DStandardE
;$)8) JJ81;C16N4 > A AND DStandardIdE " scopeIidentit(()<=N<JA %arcar(RA)<=JA"<Ne# Standard<
go
e*ec spIe*ecutes3l N<INS)84 DdboE!DStudentE(DStudentNameE= DStandardIdE)
5AL6)S (JA= JB)
S)L)C4 DStudentIDE
7819 DdboE!DStudentE
;$)8) JJ81;C16N4 > A AND DStudentIDE " scopeIidentit(()<=N<JA %arcar(RA)=JB int<=JA"<Ne#
Single Student<=JB"VB
go
e*ec spIe*ecutes3l N<INS)84 DdboE!D4eacerE(D4eacerNameE= DStandardIdE)
5AL6)S (JA= N6LL)
S)L)C4 D4eacerIdE
7819 DdboE!D4eacerE
;$)8) JJ81;C16N4 > A AND D4eacerIdE " scopeIidentit(()<=N<JA %arcar(RA)<=JA"<Ne# 4eacer<
go
e*ec spIe*ecutes3l N<INS)84 DdboE!DCourseE(DCourseNameE= DLocationE= D4eacerIdE)
5AL6)S (JA= N6LL= JB)
S)L)C4 DCourseIdE
7819 DdboE!DCourseE
;$)8) JJ81;C16N4 > A AND DCourseIdE " scopeIidentit(()<=N<JA %arcar(RA)=JB int<=JA"<Ne#
Course /or single student<=JB"U@
go
e*ec spIe*ecutes3l N<INS)84 DdboE!DStudentCourseE(DStudentIdE= DCourseIdE)
5AL6)S (JA= JB)
<=N<JA int=JB int<=JA"W@=JB"N,
go

"own$oad samp$e pro2ect 'or the demo.

&1. Apdate Entity >raph usin, '1Conte6t:
8pdate an entity *raph in disconnected scenario is a comp$e4 task. It is easy to add new entity *raph in disconnected mode .ut
to update an entity *raph needs care'u$ desi*n consideration.

1ro.$em in updatin* an entity *raph in disconnected scenario is that conte4t doesnAt know what operation was per'ormed on it
at c$ient side. As per the 'o$$owin* 'i*ure= new conte4t doesnAt know the state o' each entityB


We need to identi'y states o' each entity in the entity *raph .e'ore ca$$in* Save!ha*es method o' conte4t. &here are di''erent
patterns to identi'y entity state which we need to consider in desi*nin* data $ayer with Entity Framework.

atterns of Identifyin, Entity +tate in disconnected scenario:

&here are 'o$$owin* ways D.ut not $imitedE to identi'y entity state in disconnected scenarioB
1. 8sin* 1rimaryOey DIdE property o' an entity
2. <avin* state property in entity set

.ote: :ou can desi*n your own way to identity entity state .ased on your architecture. &his is 2ust 'or $earnin* purpose.

1* Asin, rimaryBey property of an entity:

:ou can use 1rimaryOey DIdE property o' each entity to determine its entity state. <owever= you have to decide 'o$$owin*
architectura$ ru$eB
o Each type o' entity must have Id property D1OE
o "e'au$t va$ue o' Id property shou$d .e -


As you can see in the a.ove 'i*ure that c$ient 'etch Standard and &eacher entity *raph and do some operation on it and then
send it to !onte4t 2 to save the chan*es.

In the disconnected scenario= conte4t2 doesnAt know state o' each entity. It has to determine the state o' the Standard entity .y
usin* StandardId and the state o' the &eacher entity .y usin* &eacherId property. I' StanardId and &eacherI" va$ue is 3ero that
means it is new entity and i' it is not 3ero then it is modi'ied entity.

In the a.ove 'i*ure= Standard= &eacher 1 and &eacher 2 has non93ero Id property va$ue so they are marked as #odi'ied and
&eacher 3 Id is 3ero so it is marked as Added.

5e$ow code snippet use Id property to mark entity stateB

Standard disconnectedStandard " null;
using (%ar conte*t " ne# ScoolD+)ntities())
{
conte*t!Con/iguration!Cro*(Creation)nabled " /alse;
disconnectedStandard " conte*t!Standards!;ere(s "> s!StandardId "" RX)!Include(s ">
s!4eacers)!7irst1rDe/ault<Standard>();
}
&&6pdate Standard in disconnected mode
disconnectedStandard!StandardName " 0)dited Standard Name0;

&&6pdate teacers collection b( editing /irst teacer and adding ne# teacer
disconnectedStandard!4eacers!)lementAt(A)!4eacerName " 0)dited 4eacer Name0;
disconnectedStandard!4eacers!Add(ne# 4eacer() { 4eacerName " 0Ne# 4eacer0= StandardId "
disconnectedStandard!StandardId });
using (%ar ne#Conte*t " ne# ScoolD+)ntities())
{
&&marT standard based on StandardId
ne#Conte*t!)ntr((disconnectedStandard)!State " disconnectedStandard!StandardId "" A Y
)ntit(State!Added L )ntit(State!9odi/ied;
&&marT teacer based on StandardId
/oreac (4eacer tcr in disconnectedStandard!4eacers)
ne#Conte*t!)ntr((tcr)!State " tcr!4eacerId "" A Y )ntit(State!Added L
)ntit(State!9odi/ied;


ne#Conte*t!Sa%eCanges();
}
"dvanta,e:
o ;o need 'or e4tra codin*?processin* to determine entity state.
o 7ood per'ormance.

'isadvanta,e:
o Every entity types needs to have an Id property. It cannot determine states o' the entity that do not have Id property.
o !annot identi'y 8nchan*ed entity. It set #odi'ied state even i' entity is not chan*ed at a$$. So unnecessary data.ase
update statement 'or unchan*ed entity.
o !annot hand$e de$ete entity scenario. It needs to hand$e de$etion separate$y.

#* Cavin, +tate property in every entity:

Another way to determine entity state is to have State property in every entity type and set appropriate state 'rom c$ient side in
disconnected mode. So then we 2ust need to set entity state as per the state property o' entity o.2ect .e'ore ca$$in*
Save!han*es o' new conte4t.

E6ample:
First o' a$$= create IEntityState inter'ace with enum property ca$$ed C.2ectStateB

inter/ace I)ntit(1b2ectState
{
)ntit(1b2ectState 1b2ectState { get; set; }
}
public enum )ntit(1b2ectState
{
Added=
9odi/ied=
Deleted=
6ncanged
}
;ow= imp$ement IEntityC.2ectState in each entity c$ass= e.*. Standard and &eacher entity .e$owB

public partial class StandardLI)ntit(1b2ectState
{
public Standard()
{
tis!Students " ne# $asSet<Student>();
tis!4eacers " ne# $asSet<4eacer>();
}

public int StandardId { get; set; }
public string StandardName { get; set; }
public string Description { get; set; }

public %irtual ICollection<Student> Students { get; set; }
public %irtual ICollection<4eacer> 4eacers { get; set; }
DNot9appedE
public )ntit(1b2ectState 1b2ectState
{
get;
set;
}
}
public partial class 4eacerLI)ntit(1b2ectState
{
public 4eacer()
{
tis!Courses " ne# $asSet<Course>();
}

public int 4eacerId { get; set; }
public string 4eacerName { get; set; }
public Nullable<int> StandardId { get; set; }

public %irtual ICollection<Course> Courses { get; set; }
public %irtual Standard Standard { get; set; }
DNot9appedE
public )ntit(1b2ectState 1b2ectState
{
get;
set;
}
}
Set appropriate state in disconnected mode on c$ient sideB

4eacer e*isting4eacer " null;
using (%ar conte*t " ne# ScoolD+)ntities())
{
conte*t!Con/iguration!Cro*(Creation)nabled " /alse;
e*isting4eacer " conte*t!4eacers!7irst1rDe/ault<4eacer>();
}
Standard disconnectedStandard " ne# Standard() { StandardName " 0Ne# Standard0= 1b2ectState "
)ntit(1b2ectState!Added };
e*isting4eacer!1b2ectState " )ntit(1b2ectState!9odi/ied;
&&add e*isting teacer(in db) to standard
disconnectedStandard!4eacers!Add(e*isting4eacer);
&&add ne# standard
disconnectedStandard!4eacers!Add(ne# 4eacer() { 4eacerName " 0Ne# teacer0= StandardId "
disconnectedStandard!StandardId= 1b2ectState " )ntit(1b2ectState!Added });

Set entity state as per C.2ectState .e'ore ca$$in* Save!han*es.

using (%ar ne#Conte*t " ne# ScoolD+)ntities())
{
&&cecT te 1b2ectState propert( and marT appropriate )ntit(State
i/ (disconnectedStandard!1b2ectState "" )ntit(1b2ectState!Added)
ne#Conte*t!)ntr((disconnectedStandard)!State " S(stem!Data!)ntit(!)ntit(State!Added;
else i/ (disconnectedStandard!1b2ectState "" )ntit(1b2ectState!9odi/ied)
ne#Conte*t!)ntr((disconnectedStandard)!State "S(stem!Data!)ntit(!)ntit(State!9odi/ied;
else i/ (disconnectedStandard!1b2ectState "" )ntit(1b2ectState!Deleted)
ne#Conte*t!)ntr((disconnectedStandard)!State " S(stem!Data!)ntit(!)ntit(State!Deleted;
else
ne#Conte*t!)ntr((disconnectedStandard)!State " S(stem!Data!)ntit(!)ntit(State!6ncanged;
&&cecT te 1b2ectState propert( o/ eac teacer and marT appropriate )ntit(State
/oreac (4eacer tcr in disconnectedStandard!4eacers)
{
i/ (tcr!1b2ectState "" )ntit(1b2ectState!Added)
ne#Conte*t!)ntr((tcr)!State " S(stem!Data!)ntit(!)ntit(State!Added;
else i/ (tcr!1b2ectState "" )ntit(1b2ectState!9odi/ied)
ne#Conte*t!)ntr((tcr)!State " S(stem!Data!)ntit(!)ntit(State!9odi/ied;
else i/ (tcr!1b2ectState "" )ntit(1b2ectState!Deleted)
ne#Conte*t!)ntr((tcr)!State " S(stem!Data!)ntit(!)ntit(State!Deleted;
else
ne#Conte*t!)ntr((tcr)!State " S(stem!Data!)ntit(!)ntit(State!6ncanged;
}
&&sa%e canges
ne#Conte*t!Sa%eCanges();
}
"dvanta,e:
o ;o need 'or e4tra codin*?processin* to determine entity state
o <and$es Added= #odi'ied= "e$eted and 8nchan*ed states proper$y
o ;o unnecessary update ca$$ 'or unchan*ed entities.

'isadvanta,e:
o ;eed to set appropriate states o' each entity in disconnected mode. So need to .e e4tra care'u$ in disconnected mode.
&#. Concurrency in Entity Framework:
Entity Framework supports Cptimistic !oncurrency .y de'au$t. In the optimistic concurrency= EF saves the entity to the
data.ase in the hope that the same data has not chan*ed since the entity was $oaded. I' it 'inds that data has chan*ed then an
e4ception is thrown and you must reso$ve the con'$ict .e'ore attemptin* to save it a*ain.

/etJs see how you can hand$e optimistic concurrency with Student entity.

First o' a$$= you need to have rowversion co$umn in the Student ta.$e In order to hand$e concurrency with Stuent entity.
0owversion is is a datatype in S)/ Server that automatica$$y *enerates uni@ue .inary num.er whenever insert or update
operation per'ormed in a ta.$e. &he rowversion datatype is 2ust an incrementin* num.er. 0owevesion is synonym 'or the
timestamp datatype. 5oth are same.

!reate new co$umn 0ow6ersion in Student ta.$e with timestamp datatype as .e$owB


.ote: 6a$ue o' 0ow6ersion wi$$ .e added and updated automatica$$y .y the data.se in Insert and 8pdateoperation.

;ow= create new Entity "ata #ode$ or update an e4istin* data mode$ .y ri*ht c$ickin* on desi*ner 9H Apdate (odel From
'ata1ase 9H 0e'resh Student ta.$e. So now= you wi$$ see 0ow6ersion property added in the Student entity.

;ow= you need to app$y concurrency mode to fi6ed .y ri*ht c$ickin* on 9ow@ersion property in the Student entity Dri*ht c$ick
on 0ow6ersion property not Student entityE 9H se$ect 1roperty. !han*e !oncurrency #ode to Fi4ed 'rom ;one in the property
window as .e$owB


EF wi$$ now inc$ude 0ow6ersion co$umn in the where c$ause whenever you do update operation and i' rowversion va$ue is
di''erent than in where c$ause then it wi$$ throw '1ApdateConcurrencyE6ection.

Fo$$owin* code shows that 8ser1 and 8ser2 *et the same student and update Student;ame at the same timeB

Student studentB;it6serB " null;
Student studentB;it6ser, " null;
&&6ser B gets student
using (%ar conte*t " ne# ScoolD+)ntities())
{
conte*t!Con/iguration!Cro*(Creation)nabled " /alse;
studentB;it6serB " conte*t!Students!;ere(s "> s!StudentID "" B)!Single();
}
&&6ser , also get te same student
using (%ar conte*t " ne# ScoolD+)ntities())
{
conte*t!Con/iguration!Cro*(Creation)nabled " /alse;
studentB;it6ser, " conte*t!Students!;ere(s "> s!StudentID "" B)!Single();
}
&&6ser B updates Student name
studentB;it6serB!StudentName " 0)dited /rom userB0;
&&6ser , updates Student name
studentB;it6ser,!StudentName " 0)dited /rom user,0;


now= 8ser1 saves his chan*es .e'ore 8ser2. So when user2 trys to save the chan*es= he wi$$ *et concurrency e4ectionB

&&6ser B sa%es canges /irst
using (%ar conte*t " ne# ScoolD+)ntities())
{
tr(
{
conte*t!)ntr((studentB;it6serB)!State " )ntit(State!9odi/ied;
conte*t!Sa%eCanges();
}
catc (Db6pdateConcurrenc()*ception e*)
{
Console!;riteLine(01ptimistic Concurrenc( e*ception occured0);
}
}
&&6ser , sa%es canges a/ter 6ser B!
&&6ser , #ill get concurrenc( e*ection
&&because Create1r9odi/iedDate is di//erent in te database
using (%ar conte*t " ne# ScoolD+)ntities())
{
tr(
{
conte*t!)ntr((studentB;it6ser,)!State " )ntit(State!9odi/ied;
conte*t!Sa%eCanges();
}
catc (Db6pdateConcurrenc()*ception e*)
{
Console!;riteLine(01ptimistic Concurrenc( e*ception occured0);
}
}
Concurrency in Code-First:

:ou can create timestamp property in code9'irst .y usn* X&imestampY attri.ute. #ake sure property type is .yteXY .ecause
timestamp is .inary in !>.

D4imestampE
public b(teDE 8o#5ersion { get; set; }

EF inc$udes property in where c$ause in update operation i' the property is marked with&imestamp attri.ute.

:ou can reso$ve concurrency e4ection many ways. 6isit msdn on detai$ed in'ormation on how to reso$ve optimistic concurrency.

"own$oad samp$e pro2ect 'or concurrency demo.

"own$oad samp$e pro2ect 'or the demo.

&&. +tored rocedure in Entity Framework:
Entity Framework has a.i$ity to automatica$$y .ui$d native commands 'or data.ase .ased on your /I;) to Entities or Entity S)/
@ueries= as we$$ as .ui$d the commands 'or insertin*= updatin*= or de$etin* data= you may want to override these steps and use
your own prede'ined stored procedures. :ou can use stored procedures main$y 'or either to *et the data or add?update?de$ete
the records to one or mu$tip$e data.ase ta.$es.

Stored procedures and user9de'ined 'unctions D8"FsE in the data.ase are represented as 'unctions in entity 'ramework. So
E"# wonAt have any entity or other stu'' 'or stored procedures in the E"# desi*ner.

<ere= we wi$$ add 'o$$owin* stored procedure 7et!ourses5yStudentId into E"# that returns a$$ the courses assi*ned to
particu$ar studentB
C8)A4) C81C)D68) DdboE!D?etCourses+(StudentIdE
ZZ Add te parameters /or te stored procedure ere
JStudentId int " null
AS
+)?IN
ZZ S)4 N1C16N4 1N added to pre%ent e*tra result sets /rom
ZZ inter/ering #it S)L)C4 statements!
S)4 N1C16N4 1N;
ZZ Insert statements /or procedure ere
select c!courseid= c!coursename=c!Location= c!4eacerId
/rom student s
le/t outer 2oin studentcourse sc on sc!studentid " s!studentid
le/t outer 2oin course c on c!courseid " sc!courseid
#ere s!studentid " JStudentId
)ND
First o' a$$= create new A"C.;et Entity "ata #ode$ usin* EF 'esi,ner from data1ase.


Se$ect 7et!ourses5yStudentId. #ake sure Import selected stored procedures and functions into the entity
model check.o4 is se$ected and then c$ick Finish.


:ou wou$d see in 7et!ourses5yStudentId added in Function Imports with new comp$e4 type 7et!ourses5yStudentIdG0esu$t
in #ode$ 5rowser. Whenever you import stored procedure into mode$= it creates new comp$e4 type with the name )s#
name*G0esu$t .y de'au$t.


7et!ourses5yStudentId returns same 'ie$ds de'ined in !ourse entity. So we donAt need to add new comp$e4 type 'or return
data 'rom 7et!ourses5yStudentId. :ou can chan*e it .y ri*ht c$ick on 7et!ourses5yStudentId in 'unction imports and se$ect
Edit. !heck Entities and se$ect !ourse 'rom dropdown in popup window as .e$owB



:ou wou$d see 'unction in conte4t c$ass 'or 7et!ourses5yStudentId as .e$owB


So now you ca$$ 7et!ourses5yStudentId and *et the resu$t as .e$owB

using (%ar conte*t " ne# ScoolD+)ntities())
{
%ar courses " conte*t!?etCourses+(StudentId(B);
/oreac (Course cs in courses)
Console!;riteLine(cs!CourseName);
}
A.ove code wi$$ e4ecute 'o$$owin* statementB

exec +dbo,.+"etCourses-yStudent.d, /Student.d=0

/earn how to use stored procedure 'or !8" operation in the ne4t chapter.Z
&3. C9A' usin, +tored rocedure:
In the previous chapter we have seen how to *et data usin* stored procedure. In this chapter= we wi$$ use stored procedures 'or
!8" Dcreate= update= de$eteE operation usin* ".!onte4t. &hat means conte4t wi$$ e4ecute stored procedure instead o' ""/
statements on conte4t.Save!han*esDE.

We wi$$ use spGInsertStudentIn'o stored procedure to insert new student into data.ase= spG8pdateStudent to update the
student and spG"e$eteStudent to de$ete the student in the data.ase.

+pDInsert+tudentInfo:
C8)A4) C81C)D68) DdboE!DspIInsertStudentIn/oE
ZZ Add te parameters /or te stored procedure ere
JStandardId int " null=
JStudentName %arcar
AS
+)?IN
ZZ S)4 N1C16N4 1N added to pre%ent e*tra result sets /rom
ZZ inter/ering #it S)L)C4 statements!
S)4 N1C16N4 1N;
INS)84 IN41 DScoolD+E!DdboE!DStudentE(DStudentNameE=DStandardIdE)
5AL6)S(JStudentName= JStandardId)
S)L)C4 SC1C)IID)N4I4G() AS StudentId
)ND
spDApdate+tudent:
C8)A4) C81C)D68) DdboE!DspI6pdateStudentE
ZZ Add te parameters /or te stored procedure ere
JStudentId int=
JStandardId int " null=
JStudentName %arcar
AS
+)?IN
ZZ S)4 N1C16N4 1N added to pre%ent e*tra result sets /rom
ZZ inter/ering #it S)L)C4 statements!
S)4 N1C16N4 1N;
6pdate DScoolD+E!DdboE!DStudentE
set StudentName " JStudentName=StandardId " JStandardId
#ere StudentID " JStudentId;
)ND
spD'elete+tudent
C8)A4) C81C)D68) DdboE!DspIDeleteStudentE
ZZ Add te parameters /or te stored procedure ere
JStudentId int
AS
+)?IN
ZZ S)4 N1C16N4 1N added to pre%ent e*tra result sets /rom
ZZ inter/ering #it S)L)C4 statements!
S)4 N1C16N4 1N;
D)L)4) 7819 DdboE!DStudentE
#ere StudentID " JStudentId
)ND

First o' a$$= add these stored procedures into E"# and make sure Import selected stored procudures and function into the
entity model check.o4 is unchecked .ecause we wi$$ map these procedures with Student entity direct$y.


So now= #ode$ 5rowser wi$$ add procedures into Stora*e mode$ .ut not in Function Imports


;ow= in the E"# desi*ner= ri*ht c$ick on Student entity and se$ect Stored 1rocedure #appin* to open #appin* detai$sB


In the #appin* "etai$s= you wi$$ see SSe$ect Insert FunctionH= SSe$ect 8pdate FunctionH= SSe$ect "e$ete FunctionH. Se$ect
appropriate stored procedure 'or each one e*. Se$ect spGInsertStudentIn'o 'or Insert 'unction as .e$owB


spGInsertStudentIn'o returns new auto *enerated StudentId. So map that with Student EntityAs StudentI" as .e$owB


!omp$ete the mappin* o' Insert= 8pdate and "e$ete procudures as .e$owB


;ow= we need to va$idate it .e'ore e4ecutin* 2ust to make sure that there wi$$ not .e any run time error. &o do so= ri*ht c$ick on
Student entity in the desi*ner and c$ick @alidate and make sure that there is no warnin*s or errorsB


So now= you can add= update and de$ete student as .e$owB
using (%ar conte*t " ne# ScoolD+)ntities())
{
Student ne#Student " ne# Student() { StudentName " 0Ne# Student using SC0};
conte*t!Students!Add(ne#Student);
&&#ill e*ecute spIInsertStudentIn/o
conte*t!Sa%eCanges();
ne#Student!StudentName " 0)dited student using SC0;
&&#ill e*ecute spI6pdateStudent
conte*t!Sa%eCanges();
conte*t!Students!8emo%e(ne#Student);
&&#ill e*ecute spIDeleteStudentIn/o
conte*t!Sa%eCanges();
}
A.ove code wi$$ e4ecute 'o$$owin* stored procedures on each Save!han*esDEB
e*ec DdboE!DspIInsertStudentIn/oE JStandardId"N6LL=JStudentName"<Ne# Student using SC<
go
e*ec DdboE!DspI6pdateStudentE JStudentId"WN=JStandardId"N6LL=JStudentName"<)dited student using
SC<
go
e*ec DdboE!DspIDeleteStudentE JStudentId"WN
go
.ote: Cnce conte4t ca$$ Save!ha*nes a'ter addin* a new student= it assi*n new StudentI" to StudentI" property o' the
Student entity .ecause spGInsertStudentIn'o returns StudentId. &his is necessary in order to use that entity o.2ect 'or 'urther
operation.


"own$oad samp$e pro2ect 'or the demo.
&4. (i,ration from Entity Framework 3.1=3.& to Entity Framework 4.5
&o mi*rate your e4istin* Entity Framework 4.4 pro2ect to Entity Framework .- usin* 6S2-12= 'irst tar*et .;E& Framework 4.B


Second= remove e4istin* Entity Framework 4.1?4.3 re'erence and insta$$ Entity Framework .- 'rom ;u7etB


Search Entity Framework on$ine and insta$$ it. #ake sure that version is .-B


I' you check version o' Entity 'ramework re'erence then it shou$d .e .-.-.-B


I' you open your e4istin* data mode$ D.edm4E 'i$e then it may *ive error .ecause it mi*ht .e usin* E"#N version 2.- Dopen
edm4 as N#/E. !$ick on I#odi'yA $ink on the desi*ner and it wi$$ .e modi'ied to version 3.-.

So now your e4istin* Entity Framework pro2ect wi$$ work in Entity Framework .- without any ma2or chan*es.
&8. Enum in Entity Framework 4.5
:ou can now have Enum in Entity Framework .- pro2ect that tar*ets .;E& 'ramework 4..

Enum can .e created 'or 'o$$owin* data typesB
Int1%
Int32
Int%4
5yte
S5yte

:ou can create and use Enum type in your entity data mode$ .y three wayB
1. !onvert an e4istin* property o' entity to Enum 'rom E"# desi*ner
2. Add ;ew Enum 'rom E"# desi*ner
3. 8se e4istin* Enum type 'rom di''erent namespace
For demo purpose= we have inc$uded &eacher&ype inte*er co$umn in &eacher ta.$e o' Schoo$"5 . &eacher&ype 1 is 'or
permanent teacher= 2 is 'or contractor teachers and 3 is 'or *uest teachers.

1. Convert an e6istin, property to Enum:

;ow $etAs see how to convert &eacher&ype to Enum.

First= ri*ht c$ick on &eacher&ype property o' &eacher entity and c$ick I!onvert to EnumA in conte4t menu.


It wi$$ open IAdd Enum &ypeA dia$o* .o4 where you can enter IEnum &ype ;ameA= se$ect I8nder$yin* &ypeA and Enum mem.er
names. For e4amp$eB


A'ter convertin* it to Enum= you can see &eacher&ype as Enum &ype in #ode$ 5rowser as .e$owB


A$so= you can see type o' &eacher&ype property is converted to &eacher&ype EnumB


So now you can use &eacher&ype Enum in !08" operation usin* "5!onte4t. For e4amp$eB

using (%ar ct* " ne# ScoolD+)ntities())
{
4eacer tcr " ne# 4eacer();
tcr!4eacerName " 0Ne# 4eacer0;
&&assign enum %alue
tcr!4eacer4(pe " 4eacer4(pe!Cermanent;
ct*!4eacers!Add(tcr);
ct*!Sa%eCanges();
}

#. "dd .ew Enum from 'esi,ner:

:ou can a$so add new Enum .y ri*ht c$ick on E"# desi*ner and se$ect Add [ Enum &ype. It wi$$ open same JAdd Enum &ypeJ
dia$o* .o4 where you can enter enum mem.ers.


A'ter creatin* Enum &ype you can chan*e type o' &eacher&ype property to new$y created &eacher&ype Enum 'rom the property
window.

&. If you already have Enum type created in your code then you can use that as data type of any entity property.

&o use e4istin* Enum type= ri*ht c$ick on desi*ner [ Add ;ew [ Enum &ype. Enter Enum &ype ;ame in the dia$o* .o4. "o
not enter mem.er .ecause you a$ready has it in your code.

;ow= se$ect J0e'erence e4terna$ typeJ check.o4 and enter namespace o' your e4istin* enum and c$ick CO. &his wi$$ add Enum
type in #ode$ .rowser. So now you can assi*n this Enum type to any property o' an entity 'rom property window.

.ote: Se$ect ISet F$a*s attri.uteA i' you want to use .itwise operators with your Enum.

37. Spatial Data type support in Entity Framework 5.0
#S S)/ Server 2--+ introduced spatia$ data type *eo*raphy that represents data in a round9earth coordinate system and
*eometry that represent data in a Euc$idean D'$atE coordinate system.

Entity Framework .- is now supports spatia$ data types ".7eo*raphy and ".7eometry. /etAs see how we can use these data
types.

For demo purpose we have chan*ed data type o' /ocation co$umn o' !ourse ta.$e to *eo*raphy in S)/ Server 2--+ as .e$owB


Cnce you create entity data mode$ D.edm4E 'rom this data.ase= you can check the type o' /ocation property o' !ourse entity is
System."ata.Spatia$."57eo*raphy as .e$owB

public partial class Course
{
public Course()
{
tis!Students " ne# $asSet<Student>();
}

public int CourseId { get; set; }
public string CourseName { get; set; }
public Nullable<int> 4eacerId { get; set; }
public S(stem!Data!Spatial!Db?eograp( Location { get; set; }

public %irtual 4eacer 4eacer { get; set; }
public %irtual ICollection<Student> Students { get; set; }
}

:ou can now use /ocation property in !08" operation usin* "5!onte4t. For e4amp$eB

using (%ar ct* " ne# ScoolD+)ntities())
{
ct*!Courses!Add(ne# Course() { CourseName " 0Ne# Course0=
Location " Db?eograp(!7rom4e*t(0C1IN4(ZB,,!@VA WN!VRV)0) });
ct*!Sa%eCanges();
}

6isit httpB??msdn.microso't.com?en9us?$i.rary?cc2+-(%%.asp4 'or *eo*raphy data type and httpB??msdn.microso't.com?en9
in?$i.rary?cc2+-4+(.asp4 'or *eometry data type o' #S S)/ Server 2--+.
9E@I0A+
.EET
&;. Ta1le-@alued Function in Entity Framework 4.5
Entity Framework .- support &a.$e9va$ued 'unctions o' S)/ Server.

&a.$e9va$ued 'unctions are simi$ar to stored procedure with one key di''erenceB the resu$t o' &6F is composa.$e that means
resu$ts o' &6F can .e used in a /I;) @uery.

We have created &6F 7et!ourse/ist5yStudentI" in the data.ase that wi$$ return a$$ the courses o' particu$ar student. For
e4amp$eB

6S) DScoolD+E
?1
&PPPPPP 1b2ectL 6serDe/ined7unction DdboE!D?etCourseList+(StudentIDE
S)4 ANSIIN6LLS 1N
?1
S)4 '614)DIID)N4I7I)8 1N
?1
C8)A4) 76NC4I1N DdboE!D?etCourseList+(StudentIDE
(
ZZ Add te parameters /or te /unction ere
JstudentID int
)
8)468NS 4A+L)
AS
8)468N
(
ZZ Add te S)L)C4 statement #it parameter re/erences ere
select c!courseid= c!coursename=c!Location= c!4eacerId
/rom student s le/t outer 2oin studentcourse sc on sc!studentid " s!studentid le/t outer 2oin
course c on c!courseid " sc!courseid
#ere s!studentid " JstudentID
)

;ow update your E"# and add this &6F into E"#. 0i*ht c$ick on the desi*ner [ se$ect 8pdate #ode$ 'rom "ata.ase..


E4pand Stored 1rocedures and Functions node [ e4pand schema node Dd.o schema in our caseE [ se$ect
J7et!ourse/ist5yStudentI"J and c$ick Finish. #ake sure that check.o4 'or JImport se$ected procedures and 'unctions into the
entity mode$J Dthis wi$$ import 'unction automatica$$yE.


A'ter you imported 'unction= you can veri'y itB Cpen #ode$ 5rowser [ e4pand Function Imports [ ri*ht c$ick on imported
'unction J7et!ourse/ist5yStudentI"J [ c$ick EditB


:ou can see that E"# has automatica$$y created comp$e4 type 7et!ourse/ist5yStudentI"G0esu$t as return co$$ection type.


:ou can a$so se$ect e4istin* entity as return type i' &6F returns same co$umns as entityB


;ow= you can use &6F with "5!onte4t. For e4amp$eB

using (%ar ct* " ne# ScoolD+)ntities())
{
&&)*ecute 457 and /ilter result
%ar courseList " ct*!?etCourseList+(StudentID(B)!;ere(c "> c!Location "" 0Cit(B0)
!4oList<?etCourseList+(StudentIDI8esult>();

/oreac (?etCourseList+(StudentIDI8esult cs in courseList)
Console!;riteLine(0Course NameL {A}= Course LocationL {B}0=
cs!CourseName= cs!Location);
}


&<. Batch Import of +tored rocedures in Entity Framework 4.5
1rior to Entity Framework .-= you have to manua$$y import the stored procedure as a 'unction. ;ow with Entity Framework .-=
you can import mu$tip$e stored procedures automatica$$y as a 'unctions when you add entity data mode$ or update it. For
e4amp$e= se$ect mu$tip$e stored procedures and 'unctions in Entity "ata #ode$ Wi3ard then se$ect check.o4 JImport se$ected
stored procedures and 'unctions into the entity mode$J and then c$ick FinishB


;ow= open #ode$ 5rowser and check that it has automatica$$y created 'unction imports 'or a$$ these procedures and 'unctions
and a$so created comp$e4 types as their return typeB


:ou can edit 'unction import .y ri*ht c$ick on procedure name and se$ect Edit. :ou can chan*e return type as entities or Sca$arB


Cnce you edit 'unction import then you shou$d make sure that it wi$$ not *ive any run time errors .y ri*ht c$ick on procedure and
se$ect J6a$idateJB


So this way you can .atch import o' stored procedures and 'unctions.
35. (ultiple 'ia,rams in Entity Framework 4.5
6isua$ Studio 2-12 provides 'aci$ity to sp$it desi*n time visua$ representation o' the entity data mode$. &his means that you can
have mu$tip$e dia*rams 'or one entity data mode$.

:ou can create new dia*ram .y mu$tip$e wayB
1. Add new dia*ram and dra* and drop entities 'rom #ode$ 5rowser
2. #ove entities 'rom e4istin* dia*ram to new dia*ram
1. "dd new dia,ram and dra, and drop entities from (odel Browser:

:ou can add new dia*ram .y ri*ht c$ickin* on "ia*rams node o' mode$ .rowser and se$ect JAdd ;ew "ia*ramJB


:ou can rename the dia*ram= 'or e4amp$eB Student"ia*ram wi$$ inc$ude a$$ student re$ated entitiesB


;ow= you can dra* and drop Student and StudentAdress entities to this new dia*ramB


#. (ove entities from e6istin, dia,ram to new dia,ram:

:ou can a$so move entities 'rom e4istin* dia*ram to new dia*ram. For e4amp$e i' you want to move &eacher and !ourse
entities to new dia*ram then se$ect those entities in e4istin* dia*ram and ri*ht c$ick and se$ect J#ove to ;ew "ia*ramJ 'rom
conte4t menuB


It wi$$ create new dia*ram and move &eacher and !ourse entities to new dia*ram as .e$owB


So this way you can create new dia*ram 'rom e4istin* dia*ram.

:ou can a$so inc$ude re$ated entities o' particu$ar entity. For e4amp$e= ri*ht c$ick on Student entity [ se$ect JInc$ude 0e$atedJ.
Standard and !ourse entities wi$$ a$so .e inc$uded .ecause Student has their re'erence propertyB



Additiona$$y= you can a$so move properties up or down .y ri*ht c$ick on the property [ se$ect #ove 1roperty [ se$ect
81?"own etc. as .e$owB


"i''erence .etween de$ete and removeB

:ou can remove the entity 'rom the dia*ram .y ri*ht c$ick on entity and se$ect I0emove 'rom dia*ramA.


0emove 'rom "ia*ram wi$$ on$y remove entity 'rom the dia*ram whereas J"e$ete 'rom #ode$J wi$$ de$ete the entity 'rom entity
data mode$. So you wonAt .e a.$e to use that entity at a$$.
31. Colored Entity in Entity Framework 4.5
:ou can chan*e the co$or o' entity in desi*ner so that it wou$d .e easy to see re$ated *roups o' entities in the desi*ner in
6S2-12. &o chan*e the co$or o' entity= se$ect the entity in the desi*ner [ *o to property window Dpress F4E [ chan*e the Fi$$
!o$or property. For e4amp$eB



&o chan*e co$or o' mu$tip$e entity at once= se$ect mu$tip$e entities and chan*e Fi$$ !o$or 'rom property windowB


Additiona$$y= you can a$so chan*e property 'ormat o' entities to either "isp$ay name or "isp$ay name and type. 0i*ht c$ick on
desi*ner [ se$ect JSca$ar 1roperty 'ormatJ [ se$ect J"isp$ay ;ame and &ypeJB


1roperties wi$$ .e disp$ay with its type as .e$owB

3#. 'ownload +ample ro2ect:
"own$oad samp$e pro2ect 'or Entity Framework .asic tutoria$s with Entity Framework .-.


Samp$e pro2ect a$ready inc$udes Schoo$"5.md' data.ase re@uired 'or the samp$e pro2ect. So attach Schoo$"5.md' to #S S)/
Server data.ase .e'ore runnin* samp$e pro2ect.




Entity Framework Code-First Approach

1. Introduction
2. What is Code-First
3. Simple Code-First Example
4. DB Initialization
5. DB Initialization Strategy

6. Turn-off DB Initializer
7. Seed Database
8. Inheritance Strategy
9. Configure Domain Classes
10. DataAnnotation

11. Fluent API
12. EntityTypeConfiguration
13. Fluent API Class Hierarchy
14. Configure One-to-One
15. Configure One-to-Many
16. Configure Many-to-Many

17. Migration
18. Automated Migration
19. Code-based Migration
20. EF Power Tools







































1. Introduction
Entity Framework introduced Code First approach from Entity Framework 4.1. This tutorial covers all the features of Entity Framework
Code-First. We will start with the basics of code-first and then we will see how we can configure one-to-one, one-to-many and many-to-
many relationship with DataAnnotation as well as Fluent API. We will also see migration which was introduced in EF 4.3. We wi ll use Entity
Framework 4.1 and 4.3/5.0 in this tutorial. You can also download sample project at the end of most of the chapters.

Audience:
This tutorial is helpful to anybody who wants to learn Entity Framework Code-First approach.

Prerequisites:
Basic knowledge of .Net Framework3.5, C#, Visual Studio 2010 and MS SQL Server is required. Also, basic knowledge of entity framework
is preferred.

So lets learn everything about code first step by step..


NEXT
2. What is Code-First?:
Entity Framework introduced Code First approach from Entity Framework 4.1. Code First is mainly useful in Domain Driven Design In the
Code First approach, you can focus on the domain design and start creating classes as per your domain requirement rather than design
your database first and then create the classes which matches your database design. Code First APIs will create the database on the fly
based on your entity classes and configuration.

So as a developer, you first start writing C#/VB.net classes rather than focusing on database design and then when you run the application,
Code First APIs will create the new database or map your classes with existing database before running your application.

So the basic workflow would be:

Write code-first application classes Hit F5 to run the application Code First API creates new database or map with existing database
from application classes Inserts default/test data into the database Finally launch the application

Lets see simple code first example in the next chapter.



3. Simple Code First Example:
Lets create first simple code first example.

Create the Class Library project in Visual Studio 2010. Write two simple Student and Standard entity classes as below (You can use Entity
Framework 4.1/4.3/5.0 for this example.):

Student Class:

public class Student
{
public Student()
{

}
public int StudentID { get; set; }
public string StudentName { get; set; }
}

Standard Class:

public class Standard
{
public Standard()
{

}
public int StandardId { get; set; }
public string StandardName { get; set; }
public string Description { get; set; }
}

Now, create context class which is derived from DBContext class with two DbSet properties, one for Student and one for Standard.

namespace SchoolDataLayer
{

public class Context: DbContext
{
public Context(): base()
{

}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
}

Now, create console project to test these classes as below:

using (var ctx = new Context())
{
Student stud = new Student() { StudentName = "New Student" };
ctx.Students.Add(stud);
ctx.SaveChanges();
}

Now, if you run the application then you will surprise to see that application run successfully.

It has successfully stored Student information into the database. But where is database and what are the tables and its columns??

This is the beauty of Code First APIs of Entity Framework. It creates the database based on parameter passed in the base constructor of
your context class. We have not passed any parameters so it will create SchoolDataLayer.Context database in local SQLEXPRESS. We
will see database initialization workflow in the next chapter.

Code-first API will also create two tables in the database, Students and Standards table based on Student and Standard class. Code First
APIs creates PrimaryKey in the table if class has either Id or ClassName + Id property. For example, Student class has StudentId
property so it will create StudentId as PK column. It will also create other columns with the same name and datatype as property names and
datatype as below.

So this way without creating database first, you can start writing application that will eventually create the database from your domain
classes.

4. Database Initialization:
Lets how database initialize in code-first application.

Following figure shows database initialization workflow based on the parameter passed in base constructor of context class which is derived
from DbContext:


As per above figure, you can pass following parameters in the base constructor:

No Parameter: If you do not pass the parameter then it creates the database in your local SQLEXPRESS with name matches your
{Namespace}.{Context class name}. eg. SchoolDataLayer.Context for following context:

public class Context: DbContext
{
public Context(): base()
{

}
}

Name: If you pass Name parameter then it creates database in the local SQLEXPRESS db server using that name. For example: below
code will create SchoolDB-CodeFirst database

public class Context: DbContext
{
public Context(): base("SchoolDB-CodeFirst")
{

}
}






ConnectionStringName: If you pass connection string name of app.config or web.config then it will create the database as per connection
string. For example, below code will create "SchoolDB-ByConnectionString" database:

public class Context: DbContext
{
public SchoolDBContext() : base("SchoolDBConnectionString")
{
}
}

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SchoolDBConnectionString"
connectionString="Data Source=.;Initial Catalog=SchoolDB-ByConnectionString;Integrated Security=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

Above Context class sends connection string name as a parameter. So it will create new "SchoolDB-ByConnectionString" database or use
existing SchoolDB-ByConnectionString database at local SQL Server (because we have mentioned '.' not SQLEXPRESS). Make sure that
you include providerName = "System.Data.SqlClient" in the connection string.


5. Database Initialization Strategies in Code-First:
You already created database after running you code first application first time, but what about second time onwards?? Will it create new
database every time you run the application? What about production environment? How to alter database when you change your domain
model? To handle these scenarios, you have to use one of the database initialization strategies.

There are four different database Initialization strategies:

1. CreateDatabaseIfNotExists: This is default initializer. As name suggests, it will create the database if not exists as per the
configuration. However, if you change the model class and then run the application with this initializer then it will throw an
exception.
2. DropCreateDatabaseIfModelChanges: This initializer drops existing database and creates new database if your model classes
(entity classes) have been changed. So you dont have to worry about maintaining your database schema when your model
classes changes.
3. DropCreateDatabaseAlways: As name suggests, this initializer drops an existing database every time you run the application
irrespective of whether your model classes have changed or not. This will be useful when you want fresh database every time you
run the application while developing.
4. Custom DB Initializer: You can also create your own custom initializer if any of the above doesnt satisfy your requirement or you
want to do some other process when it initialize the database using above initializer.
























To use one of the above DB initialization strategies, you have to set the DB Initializer using Database class in Context class as following:

public class SchoolDBContext: DbContext
{

public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>());

//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}

You can also create your custom DB initializer by inheriting one of the intializer as below:

public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
{
protected override void Seed(SchoolDBContext context)
{
base.Seed(context);
}
}

As you can see in the above code, we have created new class SchoolDBInitializer which is derived from DropCreateDatabaseAlways
initializer.

Set db initializer in the configuration file:

You can also set db initializer in the configuration file. For example, to set default initializer in app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DatabaseInitializerForType SchoolDataLayer.SchoolDBContext, SchoolDataLayer"
value="System.Data.Entity.DropCreateDatabaseAlways`1[[SchoolDataLayer.SchoolDBContext,
SchoolDataLayer]], EntityFramework" />
</appSettings>
</configuration>

You can set custom db initializer as following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DatabaseInitializerForType SchoolDataLayer.SchoolDBContext, SchoolDataLayer"
value="SchoolDataLayer.SchoolDBInitializer, SchoolDataLayer" />
</appSettings>
</configuration>

So this way you can use DB initialization strategy for your application.














6. Turn off DB Initializer in Code-First:
You can also turn of DB initializer of your application. Suppose for the production environment you dont want to lose existi ng data then you
can turn off initializer as following:

public class SchoolDBContext: DbContext
{
public SchoolDBContext() : base("SchoolDBConnectionString")
{
//Disable initializer
Database.SetInitializer<SchoolDBContext>(null);
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}

You can also turn off initializer in the configuration file, for example:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DatabaseInitializerForType SchoolDataLayer.SchoolDBContext, SchoolDataLayer"
value="Disabled" />
</appSettings>
</configuration>



7. Seed Database in Code-First:
You can insert data into your database tables in database initialization process. This will be important if you want to provi de some test data
for your application or to provide some default master data for your application.

To seed data into your database, you have to create custom DB initializer as you created in the previous chapter and override Seed
method. Following example show how you can provide default data for Standard table while initializing the School database:

public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
{
protected override void Seed(SchoolDBContext context)
{
IList<Standard> defaultStandards = new List<Standard>();

defaultStandards.Add(new Standard() { StandardName = "Standard 1", Description = "First Standard" });
defaultStandards.Add(new Standard() { StandardName = "Standard 2", Description = "Second Standard" });
defaultStandards.Add(new Standard() { StandardName = "Standard 3", Description = "Third Standard" });

foreach (Standard std in defaultStandards)
context.Standards.Add(std);

//All standards will
base.Seed(context);
}
}
















PREVIOUS
NEXT
8. Inheritance Strategy in Code-First:
In the code first approach, database schema will be created based on the design of your domain classes. You may design your domain
classes in object-oriented way where you can use inheritance and polymorphism. Object-oriented systems model has has a and is a
relationships where as SQL based relational model has only has a relationships. So how would you map object-oriented with relational
database?

There are three different approaches to represent an inheritance hierarchy:

Table per Hierarchy (TPH): This approach suggests one table for entire class inheritance hierarchy. Table includes discriminator
column which distinguish between inheritance classes.
Table per Type (TPT): This approach suggests one table for each classes thus each class will have its persistence table.
Table per Concrete class (TPC): This approach suggests one table for one concrete class but not for abstract class. So if you
inherit abstract class in multiple concrete classes then properties of abstract class will be part of each table of concrete class.

We are not going into detail here. Visit following reference link to understand it in detail:

TPH:
http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-
hierarchy-tph.aspx

TPT:
http://weblogs.asp.net/manavi/archive/2010/12/28/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-
type-tpt.aspx

TPC:
http://weblogs.asp.net/manavi/archive/2011/01/03/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-
concrete-type-tpc-and-choosing-strategy-guidelines.aspx

9. Configure Domain Classes in Code-First:
As you know that you can create entity data model from existing database in database first approach that has all the metadata information in
SSDL, CSDL and MSL so that EF can use this model in querying, change tracking, updating functionality etc.. The same way, ent ity
framework code first allows you to use your domain classes to build the model which in-tern will be used by EF in different activity. Code first
suggests certain conventions to follow by your domain classes so that EF can understand it and build the model out of it.

However, if your domain classes dont follow conventions then you also have the ability to configure your domain classes so t hat EF can
understand it and build the model out of it. There are two ways by which you can configure your domain classes:
1. DataAnnotation
2. Fluent API






















DataAnnotation:

DataAnnotation is simple attribute based configuration which you can apply on your domain classes and its properties. You can find most of
the attributes in System.ComponentModel.DataAnnotations namespace. However, DataAnnotation provides only subset of Fluent API
configurations. So if you dont find some attributes in DataAnnotation then you have to use Fluent API to configure it.

Following is an example of DataAnnotation used in Student Class:

[Table("StudentInfo")]
public class Student
{
public Student() { }

[Key]
public int SID { get; set; }

[Column("Name", TypeName="ntext")]
[MaxLength(20)]
public string StudentName { get; set; }

[NotMapped]
public int? Age { get; set; }


public int StdId { get; set; }

[ForeignKey("StdId")]
public virtual Standard Standard { get; set; }
}

Fluent API:

Fluent API configuration applied as EF building the model from your domain classes. You can inject the configurations by overriding the
DbContext classs OnModelCreating method as following:

public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
}

public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
public DbSet<StudentAddress> StudentAddress { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure domain classes using Fluent API here

base.OnModelCreating(modelBuilder);
}
}

You can use modelBuilder which is an object of DbModelBuilder class to configure domain classes.

Lets see DataAnnotation and Fluent API in detail in the next chapter.















10. DataAnnotation in Code-First:
EF Code first provides set of DataAnnotation attributes which you can apply on your domain classes and properties. You have to
include System.ComponentModel.DataAnnotations namespace to use DataAnnotation attributes. DataAnnotation basically includes
attributes for server side validations and database related attributes.

Validation Attributes:

Annotation Attribute Description
Required The Required annotation will force EF (and MVC) to ensure that property has data in it.
MinLength MinLength annotation validates property whether it has minimum length of array or string.
MaxLength MaxLength annotation maximum length of property which in-tern set maximum length of column in the database
StringLength Specifies the minimum and maximum length of characters that are allowed in a data field.

Database Schema related Attributes:

Annotation
Attribute
Description
Table Specify name of the DB table which will be mapped with the class
Column Specify column name and datatype which will be mapped with the property
Key Mark property as EntityKey which will be mapped to PK of related table.
ComplexType Mark the class as complex type in EF.
Timestamp Mark the property as a non-nullable timestamp column in the database.
ForeignKey Specify Foreign key property for Navigation property
NotMapped Specify that property will not be mapped with database
ConcurrencyCheck ConcurrencyCheck annotation allows you to flag one or more properties to be used for concurrency checking in the database when a
user edits or deletes an entity.
DatabaseGenerated DatabaseGenerated attribute specifies that property will be mapped to Computed column of the database table. So the property will
be read-only property. It can also be used to map the property to identity column (auto incremental column).
InverseProperty InverseProperty is useful when you have multiple relationship between two classes.

DataAnnotation example:

[Table("StudentInfo")]
public class Student
{
public Student(){ }

[Key]
public int SID { get; set; }

[Required(ErrorMessage="Student Name is Required" )]
[Column("Name", TypeName="ntext")]
[MaxLength(20), MinLength(2, ErrorMessage="Student name can not be 2 character or less")]
public string StudentName { get; set; }

[NotMapped]
public int? Age { get; set; }

[ConcurrencyCheck()]
[Timestamp]
public Byte[] LastModifiedTimestamp { get; set; }

public int? MathScore { get; set; }

public int? ScienceScore { get; set; }

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int? TotalScore




11. Fluent API in Code-First:
As you have seen in previous chapter that you can configure your domain classes by overriding OnModelCreating method of DBContext in
your context class. For example:

public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
}

public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
public DbSet<StudentAddress> StudentAddress { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure domain classes using Fluent API here

base.OnModelCreating(modelBuilder);
}
}


DbModelBuilder is main class by which you can configure domain classes. Configuration done by using the DbModelBuilder API takes
precedence over data annotations which in turn take precedence over the default conventions.

DbModelBuilder class has following important property and method:
Property / Method
Name
Description Return Type
Conventions Provides access to the settings of this DbModelBuilder that deal with conventions. You
can disable the conventions for the DbModelBuilder.

Entity<TEntityType>() Registers an entity type as part of the model and returns an object that can be used to
configure the entity. This method can be called multiple times for the same entity to
perform multiple lines of configuration.
EntityTypeConfiguration<TEntityType>

12. EntityTypeConfiguration Class in Code-First:
It is important to understand EntityTypeConfiguration class because it is an important class that allows configuration to be performed for an
entity type in a model. It can be obtained by calling Entity method of DbModelBuilder class:
















EntityTypeConfiguration has following important methods:

Method Name Return Type Description
HasKey<TKey> EntityTypeConfiguration Configures the primary key property(s) for this entity type.
HasMany<TTargetEntity> ManyNavigationPropertyConfiguration Configures a many relationship from this entity type.
HasOptional<TTargetEntity> OptionalNavigationPropertyConfiguration Configures an optional relationship from this entity type. Instances of the entity
type will be able to be saved to the database without this relationship being
specified. The foreign key in the database will be nullable.
HasRequired<TTargetEntity> RequiredNavigationPropertyConfiguration Configures a required relationship from this entity type. Instances of the entity
type will not be able to be saved to the database unless this relationship is
specified. The foreign key in the database will be non-nullable.
Ignore<TProperty> Void Excludes a property from the model so that it will not be mapped to the
database.
Map EntityTypeConfiguration Allows advanced configuration related to how this entity type is mapped to the
database schema.
Property<T> StructuralTypeConfiguration Configures a struct property that is defined on this type.
ToTable Void Configures the table name that this entity type is mapped to.






13. Fluent API Class Hierarchy:
Below image shows hierarchy of important Fluent API classes:



As you can see that I have separated classes by levels eg. DbModelBuilder is level 0 class because its main class in Fluent API
configuration. EntityTypeConfiguration is Level 1 class because we can set relationship between entities using this class.
ManyNavigarionConfiguration, OptionalNavigationPropertyConfiguration and RequiredNavigationPropertyConfiguration are Level 2 classes
which set some additional configuration between entities.

So, Level 1 and Level 2 classes can be used to configure relationship between the entities that will be mapped to database tables. Level 3 &
4 can be used to configure additional mapping between the entities.

Next chapters will explain how to use these classes to configure One-to-One, One-to-Many and Many-to-Many relationships using these
classes.

14. Configure One-to-One Relationship:
We are going to configure One-to-One relationship between Student and StudentAddress. As you may know that one to one relationship
happens when primary key of one table becomes PK & FK in another table. Here, StudentId is a Primary key of Student table so StudentId
should be PK and FK in StudentAddress table in order to have one to one (one to zero or one) relationship between them.

Configure one to zero or one relationship using DataAnnotation:

public class Student
{
public Student() { }

public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }

[Required]
public virtual StudentAddress StudentAddress { get; set; }

}


public class StudentAddress
{
[Key, ForeignKey("Student")]
public int StudentId { get; set; }

public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public int Zipcode { get; set; }
public string State { get; set; }
public string Country { get; set; }

public virtual Student Student { get; set; }
}

As you can see in above Student and StudentAddress class, we havent done anything special in Student class because StudentId follows
the conventions so it will become PK. Now, we use Key and ForeignKey attribute for StudentId in StudentAddress class to mark it as PK as
well as FK. So thus it will create one-to-one relationship between Student and StudentAddress.

Configure One-to-One relationship using Fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentAddress>()
.HasKey(e => e.StudentId);
modelBuilder.Entity<StudentAddress>()
.Property(e => e.StudentId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<StudentAddress>()
.HasRequired(e => e.Student)
.WithRequiredDependent(s => s.StudentAddress);

base.OnModelCreating(modelBuilder);
}

Above code will create following database:



You can check the relationship between Student and StudentAddress in the database as below:



If you create entity data model of created database then it will look like this:



You will learn how to create one-to-many relationship in the next chapter.


15. Configure One-to-Many Relationship:
We are going to configure One-to-Many relationship between Student and Standard as many students are studying in one standard.

Configure One-to-Many relationship using DataAnnotation:

Student entity class has reference property of Standard class with StandardId foreignKey proeprty and Standard class has collection
property for Students. So this DataAnnotation will result in One-to-Many relationship.

public class Student
{
public Student() { }

public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }

public int StdandardId { get; set; }

public virtual Standard Standard { get; set; }
}


public class Standard
{
public Standard()
{
Students = new List<Student>();
}
public int StandardId { get; set; }
public string StandardName { get; set; }
public string Description { get; set; }

public virtual ICollection<Student> Students { get; set; }
}














Configure One-to-Many relationship using Fluent API:

Suppose your Student and Standard entity class doesnt follow code first conventions and have different property names, for example:

public class Student
{
public Student(){ }

public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }

//StdId is not following code first conventions name
public int StdId { get; set; }

public virtual Standard Standard { get; set; }
}


public class Standard
{
public Standard()
{
StudentsList = new List<Student>();
}
public int StandardId { get; set; }
public string StandardName { get; set; }
public string Description { get; set; }

public virtual ICollection<Student> StudentsList { get; set; }
}

So you can use Fluent API to configure One-to-Many relationship between Student and Standard entity classes:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<Student>().HasRequired<Standard>(s => s.Standard)
.WithMany(s => s.StudentsList).HasForeignKey(s => s.StdId);

}

Other possible way:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<Standard>().HasMany<Student>(s => s.StudentsList)
.WithRequired(s => s.Standard).HasForeignKey(s => s.StdId);
}

Above code will create following database:


Entity Data Model in designer will look like below:




























PREVIOUS
NEXT
16. Configure Many-to-Many relationship:
We are going to configure Many-to-Many relationship between Student and Course entity classes.

Configure Many-to-Many relationship using DataAnnotation:

Student class should have collection navigation property for Course and Course should have collection navigation property for student
which will create Many-to-Many relationship between student and course as below:

public class Student
{
public Student() { }

public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }

public int StdandardId { get; set; }

public virtual ICollection<Course> Courses { get; set; }
}


public class Course
{
public Course()
{
this.Students = new HashSet<Student>();
}

public int CourseId { get; set; }
public string CourseName { get; set; }

public virtual ICollection<Student> Students { get; set; }
}

Above code will create following database where code first will create third joining table CourseStudent which will consist PK of both the
tables ie. StudentId & CourseId:



Configure Many-to-Many relationship using Fluent API:

You can use Fluent API to configure Many-to-Many relationship between Student and Course as following:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

modelBuilder.Entity<Student>().HasMany<Course>(s => s.Courses).WithMany(c => c.Students).Map(c =>
{
c.MapLeftKey("Student_id");
c.MapRightKey("Course_id");
c.ToTable("StudentAndCourse");
});

base.OnModelCreating(modelBuilder);
}

As you can see in above code that we are mapping left key (key column of Student class)with Student_id and right key (key column of
Course class) with Course_id of table "StudentAndCourse".

This will create new joining table StudentAndCourse with two PK which is also FK as below:





PREVIOUS
NEXT
17. Migration in Code-First:
Entity framework code first has different database initialization strategies prior to EF 4.3 like CreateDatabaseIfNotExists,
DropCreateDatabaseIfModelChanges or DropCreateDatabaseAlways. However, there were some problems with these strategies, for
example if you already have data (other than seed data) or existing Stored Procedures, triggers etc in your database then these strategies
used to drop the entire database and recreate it and so you lose the data and other db objects.

Entity framework 4.3 has introduced migration that automatically updates database schema when your model changes without losing any
existing data or other database objects. It uses new database initializer called MigrateDatabaseToLatestVersion.

There is two kind of Migration:
1. Automated Migration
2. Code based Migration

Lets see these migrations in detail in the next chapters.



























18. Automated Migration:
Entity framework 4.3 has introduced Automated Migration so that you dont have to maintain database migration manually in code file for
each change you make in your domain classes. You just need to run command in Package Manger Console and you will be done.

Lets see how you can use automated migration.

As you know, you dont have any database when you start writing code first application. For example, we start writing application with
Student and Course entity classes. But before running application that is before creating database first time, you have to enable automated
migration by running enable-migrations command in Package Manager Console as below:

First, open package manager console from Tools Library Package Manager Package Manager Console and then run "enable-
migrations EnableAutomaticMigration:$true" command (make sure that default project is the project where your context class is)



Once command runs successfully, it creates internal sealed Configuration class in Migration folder in your project:



If you open and see this class then you will find AutomaticMigrationsEnabled = true in the constructor.

internal sealed class Configuration : DbMigrationsConfiguration<SchoolDataLayer.SchoolDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}

protected override void Seed(SchoolDataLayer.SchoolDBContext context)
{
// This method will be called after migrating to the latest version.

// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}










You also need to set the database initializer in context class with new db initialization strategy MigrateDatabaseToLatestVersion as below:

public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolDBContext,
SchoolDataLayer.Migrations.Configuration>("SchoolDBConnectionString"));

}

public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

base.OnModelCreating(modelBuilder);
}

}

As you can see in the above code that we have passed Configuration class name which was created by command, along with context class
name.

Now you are set for automated migration. It will automatically take care of migration as and when you change the model. Run the
application and see the created database:



You will find that it has created one system table __MigrationHistory along with other tables. This is where automated migration maintains
the history of database changes.

Now lets add Standard entity class and run the application again and see that it has automatically created Standard table.

Wait a minute, this will take care if you add new entity class or remove entity class but what about adding or removing properties from any of
the entity class? To check that, lets remove Description property from Standard class and run the application.

Oops.. you will get an error message:


This is because you will lose data in description column if you remove it from Standard class. So to handle this kind of scenario you have to
set AutomaticMigrationDataLossAllowed = true in configuration class constructor along with AutomaticMigrationsEnabled = true.

Note: You can find more information about parameters we can pass to enable-migrations command using get-help enable-migrations
command. For detailed help use get-help enable-migrations detailed

So thus you can handle migration automatically.


19. Code-based Migration:
Code based migration is useful when you want more control on migration i.e. set default value of the column etc.

Code first has two commands for code based migration:

1. Add-migration: It will scaffold the next migration for the changes you have made to your domain classes
2. Update-database: It will apply pending changes to the database based on latest scaffolding code file you create using "Add-
Migration" command

Assume that you have Student and Course entity classes initially and you want to use code based migration for your application. So before
running above commands you must enable migration for your application by using enable-migrations commands in package manger as we
did it for automatic migration. This will create configuration file same as automated migration. Also, you need to set database initializer in
context class:

public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolDBContext,
SchoolDataLayer.Migrations.Configuration>("SchoolDBConnectionString"));

}

public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

base.OnModelCreating(modelBuilder);
}

}

Now, you have to create scaffold code file which consist your database requirement from your existing domain classes. You can do this by
running add-migration" command in package manger. (from Tools Library Package Manager Package Manager Console). You have
to pass the name parameter which will be part of code file name.



Add-Migration command Syntax:

Add-Migration [-Name] <String> [-Force]
[-ProjectName <String>] [-StartUpProjectName <String>]
[-ConfigurationTypeName <String>] [-ConnectionStringName <String>]
[-IgnoreChanges] [<CommonParameters>]

Add-Migration [-Name] <String> [-Force]
[-ProjectName <String>] [-StartUpProjectName <String>]
[-ConfigurationTypeName <String>] -ConnectionString <String>
-ConnectionProviderName <String> [-IgnoreChanges] [<Common Parameters>]

You can see that this command has created new file in Migration folder with name parameter you passed in command with timestamp
prefix:



After creating above file using add-migration command, you have to update the database. You can create or update the database using
update-database command. You can use verbose to see whats going on in the database:



Update-Database command syntax:

Update-Database [-SourceMigration <String>]
[-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>]
[-StartUpProjectName <String>] [-ConfigurationTypeName <String>]
[-ConnectionStringName <String>] [<CommonParameters>]

Update-Database [-SourceMigration <String>] [-TargetMigration <String>]
[-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>]
[-ConfigurationTypeName <String>] -ConnectionString <String>
-ConnectionProviderName <String> [<CommonParameters>]

At this point, database will be created or updated.

Now suppose you added more domain classes. So before running application, you have to create scaffold file for new classes by executing
"Add-Migration" command. Once it creates the file, update the database using Update-Database command. So this way you have repeat
Add-Migration and Update-Database command each time when you make any changes in your domain classes.

Rollback Database change:

Suppose you want to rollback database schema to any of the previous state then you can use Update-database command with
TargetMigration parameter as below:

update-database -TargetMigration:"First School DB schema"

Use "get-migration" command to see what migration have been applied.

Note: Use get-help command for add-migration and update-database command to see what are the parameters we can pass with this
command.


PREVIOUS
HOME
20. Entity Framework Power Tools:
Entity Framework Power Tools (currently in beta 3) has been released. EF Power Tools is useful mainly in reverse engineering and
generating read-only entity data model for code-first.

Download and install Power Tools from Visualstudiogallery

After installing it, when you right click on the C# project, you can see Entity Framework option in the context menu.

When right-clicking on a C# project, the following context menu functions are supported:
Reverse Engineer Code First - Generates POCO classes, derived DbContext and Code First mapping for an existing database.
Customize Reverse Engineer Templates - Adds the default reverse engineer T4 templates to your project for editing.



When right-clicking on a file containing a derived DbContext class, the following context menu functions are supported:
View Entity Data Model (Read-only) - Displays a read-only view of the Code First model in the Entity Model Designer.
View Entity Data Model XML - Displays the EDMX XML representing the underlying Code First model.
View Entity Data Model DDL SQL - Displays the DDL SQL corresponding to the SSDL in the underlying EDM Model.
Generate Views - Generates pre-compiled views used by the EF runtime to improve start-up performance. Adds the generated
views file to the containing project.



When right-clicking on an Entity Data Model (*.edmx) file, the following context menu function is supported:
Generate Views - Generates pre-compiled views used by the EF runtime to improve start-up performance. Adds the generated
views file to the containing project.



Visit MSDN for step-by-step demonstrates the tasks that you can accomplish with the EF Power Tools.

Entity Framework 6.0 New Features

1. Introduction
2. Async Query and Save
3. Code-based configuration
4. Db Command Logging
5. Command Interception
6. Transaction support
7. DbSet.AddRange
8. Custom Conventions
9. Stored Procedure Mapping
10. Index Attribute
11. Download Sample Project

























1. Entity Framework 6.0 Introduction:
Welcome to Entity Framework 6 tutorials section. Here, you will learn about new features introduced in Entity
Framework 6.0 with Visual Studio 2012.

Entity Framework 6.0 has introduced many new exciting features for database first (designer) and code-first
approaches.

Features for Database First (Designer) and Code-First Both:
1. Connection resiliency
2. Asynchronous query and save
3. Code-based configuration
4. Database command logging
5. Database command interception
6. Dependency Resolution
7. DbSet.AddRange/RemoveRange
8. Better Transaction Support
9. Pluggable pluralisation and singularization service
10. Testability improvements
11. Creating context with an open connection
12. Improved performance and warm-up time

Features for Code-First:
1. Custom conventions
2. Insert, update & delete stored procedures for entity CUD operation
3. Index attribute (EF 6.1)
4. Multiple context per database
5. Nested entity types
6. Custom migration operations
7. Configurable migration history table













2. Async query and Save:
You can take advantage of asynchronous execution of .net 4.5 with entity framework. EF 6 has a ability to execute a
query and command asynchronously using DbContext.

Lets see how to execute asynchronous query first and then we will see asynchronous call to context.SaveChanges.

Asynchronous Query:

private static async Task<Student> GetStudent()
{
Student student = null;

using (var context = new SchoolDBEntities())
{
Console.WriteLine("Start GetStudent...");

student = await (context.Students.Where(s => s.StudentID ==
1).FirstOrDefaultAsync<Student>());

Console.WriteLine("Finished GetStudent...");

}

return student;
}
As you can see in the above code, GetStudent method marked with async to make it asynchronous. Return type of
asynchrounous method must be Task. GetStudent returns object of Student entity so return type must
be Task<Student>.

Also, query is marked with await, this freed calling thread to do something else till it executes query and returns data.
We have used FirstOrDefaultAsync extension method of System.Data.Entity. you may use other extension methods
appropriately like SingleOrDefaultAsync, ToListAsyn etc.

Asynchronous Save:

You can call context.SaveChanges asynchronously the same way as async query:

private static async Task SaveStudent(Student editedStudent)
{

using (var context = new SchoolDBEntities())
{
context.Entry(editedStudent).State = EntityState.Modified;

Console.WriteLine("Start SaveStudent...");

int x = await (context.SaveChangesAsync());

Console.WriteLine("Finished SaveStudent...");
}

}






Getting async query result:

You can get result when asynchronous using wait method as below:
public static void AsyncQueryAndSave()
{
var student = GetStudent();

Console.WriteLine("Let's do something else till we get student..");

student.Wait();


var studentSave = SaveStudent(student.Result);

Console.WriteLine("Let's do something else till we get student.." );

studentSave.Wait();

}
As per above code, we call async method GetStudent as usual and store reference in variable student. Then we call
student.wait(), this means calling thread should wait till asynchronous method completes. So we can do other process
till we get result from asynchronous method.

Above code will have following output:




3. Code-based Configuration:
Entity Framework 6 has introduced code based configuration. So now you can configure entity framework related
settings using code which you used to do it in app.config in section. However, app.config takes precedence over code-
based configuration that means, if a configuration option is set in both code and in the config file, then the setting in the
config file is used.

Lets see how to implement code-based configuration using Entity Framework 6.

First of all, you need to create new class that derives DbConfiguration (System.Data.Entity.DbConfiguration) class :

public class FE6CodeConfig : DbConfiguration
{
public FE6CodeConfig()
{
//define configuration here
}
}
Now, you can set codeConfigurationType in config file as below:

<entityFramework codeConfigurationType="EF6DBFirstTutorials.FE6CodeConfig,
EF6DBFirstTutorials">
</entityFramework>

Or you can use DbConfigurationType attribute on context class to set code-based configuration class:





Note: EF does not support having multiple configuration classes used in the same AppDomain. If you use this attribute
to set different configuration classes for two contexts then an exception will be thrown.

So now, you can then use different methods of DbConfiguration using this in the constructor as below:






Let's see how to do different settings using code-based configuration as well as config file.

Set default connection factory:

Code-based configuration:

public class FE6CodeConfig : DbConfiguration
{
public FE6CodeConfig()
{
this.SetDefaultConnectionFactory(new
System.Data.Entity.Infrastructure.SqlConnectionFactory());
}
}
config file:

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,
EntityFramework" />
</entityFramework>
Set Database Provider:

Code-based configuration:

public class FE6CodeConfig : DbConfiguration
{
public FE6CodeConfig()
{
this.SetProviderServices("System.Data.SqlClient",
System.Data.Entity.SqlServer.SqlProviderServices.Instance);
}
}
config file:

<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Set Database Initializers:

You can set database initializers (for code-first only) using code-based configuration as below:

public class FE6CodeConfig : DbConfiguration
{
public FE6CodeConfig()
{
this.SetDatabaseInitializer<SchoolDBEntities>(new
CustomDBInitializer<SchoolDBEntities>());
}
}
config file:

<entityFramework>
<contexts>
<context type="EF6DBFirstTutorials.SchoolDBEntities, EF6DBFirstTutorials" >
<databaseInitializer type="EF6DBFirstTutorials.CustomDBInitializer ,
EF6DBFirstTutorials">
</databaseInitializer>
</context>
</contexts>
</entityFramework>



4. Database Command Logging:
Here, you are going to learn how to log commands & queries sent to the database by Entity Framework.

We used to use database tracing tool or third party tracing utility to trace database queries and command sent by Entity
Framework prior to EF 6. Now, EF 6 provides simple mechanism to log everything what Entity Framework is doing. It
logs all the activity performed by EF using context.database.Log

You can attach any method of any class which accept one string parameter and returns void.

In the following example, we use Console.Write method to log EF activities:

Example:

using (var context = new SchoolDBEntities())
{
context.Database.Log = Console.Write;
var student = context.Students
.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();

student.StudentName = "Edited Name";
context.SaveChanges();
}
Output:






You can see in the output that it logs all the activities performed by EF e.g. opening & closing connection, execution &
completion time and database queries & commands.

Context.Database.Log is aAction<string> so that you can attach any method which has one string parameter and void
return type.



















For example:

public class Logger
{
public static void Log(string message)
{
Console.WriteLine("EF Message: {0} ", message);
}
}

class EF6Demo
{

public static void DBCommandLogging()
{
using (var context = new SchoolDBEntities())
{

context.Database.Log = Logger.Log;
var student = context.Students
.Where(s => s.StudentName ==
"Student1").FirstOrDefault<Student>();

student.StudentName = "Edited Name";
context.SaveChanges();
}
}
}
Download DB First sample project for DB command logging demo.




































5. Interception:
Here, you will learn how to intercept EF when it execute database commands.

EF 6 provides ability to intercept the context using IDbCommandInterceptor before and after it performs
ExecuteNonQuery, ExecuteScalar, ExecuteReader operations to the database.

First of all, implement IDbCommandInterceptor as below:

class EFCommandInterceptor: IDbCommandInterceptor
{
public void NonQueryExecuted(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<int> interceptionContext)
{
LogInfo("NonQueryExecuted", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}

public void NonQueryExecuting(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<int> interceptionContext)
{
LogInfo("NonQueryExecuting", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}

public void ReaderExecuted(System.Data.Common.DbCommand command,
DbCommandInterceptionContextt<System.Data.Common.DbDataReader> interceptionContext)
{
LogInfo("ReaderExecuted", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}

public void ReaderExecuting(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
LogInfo("ReaderExecuting", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}

public void ScalarExecuted(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<object> interceptionContext)
{
LogInfo("ScalarExecuted", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}

public void ScalarExecuting(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<object> interceptionContext)
{
LogInfo("ScalarExecuting", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}

private void LogInfo(string command, string commandText)
{
Console.WriteLine("Intercepted on: {0} :- {1} ", command, commandText);
}
}
You can see in the above code that IDbCommandInterceptor provides six methods to execute.

Now, you need to configure interceptor either using config file or code-based configuration.

Config file:

<entityFramework>
<interceptors>
<interceptor type="EF6DBFirstTutorials.EFCommandInterceptor, EF6DBFirstTutorials">
</interceptor>
</interceptors>
</entityFramework>
Code-based config:

public class FE6CodeConfig : DbConfiguration
{
public FE6CodeConfig()
{
this.AddInterceptor(new EFCommandInterceptor());
}
}
So now, we log commands whenever DbContext executes ExecuteNonQuery, ExecuteScalar, ExecuteReader.


6. Transaction support:
Entity Framework by default wraps Insert, Update or Delete operation in a transaction whenever you execute
SaveChanges(). EF starts new transaction for each operations and complete the transaction when it operation finishes.
When you execute another such operation a new transaction is started.

EF 6 has introduced database.BeginTransaction and Database.UseTransaction to provide more control over
transaction. Now, you can execute multiple operations in a single transaction as below:

using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction(
))
{
try
{
Student std1 = new Student() { StudentName = "newstudent" };
context.Students.Add(std1);
context.Database.ExecuteSqlCommand(
@"UPDATE Student SET StudentName = 'Edited Student Name'" +
" WHERE StudentID =1"
);
context.Students.Remove(std1);

//saves all above operations within one transaction
context.SaveChanges();

//commit transaction
dbTran.Commit();
}
catch (Exception ex)
{
//Rollback transaction if exception occurs
dbTran.Rollback();
}

}
database.UseTransaction allows the DbContext to use a transaction which was started outside of the Entity Framework.



7. DbSet.AddRange & DbSet.RemoveRange:
DbSet in EF 6 has introduced new methods AddRange & RemoveRange. DbSet.AddRange adds
collection(IEnumerable) of entities to the DbContext, so you don't have to add each entity individually.

IList<Student> newStudents = new List<Student>();
newStudents.Add(new Student() { StudentName = "Student1 by addrange" });
newStudents.Add(new Student() { StudentName = "Student2 by addrange" });
newStudents.Add(new Student() { StudentName = "Student3 by addrange" });

using (var context = new SchoolDBEntities())
{
context.Students.AddRange(newStudents);
context.SaveChanges();
}
Same way, use DbSet.RemoveRange to remove collection of entities from DbSet.

IList<Student> existingStudents = ..

using (var context = new SchoolDBEntities())
{
context.Students.RemoveRange(existingStudents);
context.SaveChanges();
}
Download sample project for DbSet.AddRange demo.


8. Custom Code-First Conventions:
Code First has a set of default behaviours for the models that refer to as conventions. EF 6 provides ability to define
your own custom conventions which will be default behaviour for your models.

There are two main types of Conventions, Configuration Conventions and Model Conventions.

Configuration Conventions:

Configuration Conventions are a way to configure entities without overriding default behaviour provided in the Fluent
API. You can define a configuration convention inside your OnModelCreating event or in a custom Convention Class in
a similar way to how you would define normal entity mappings with the Fluent API.

For example, you can define primary key of entity that has property named {entity name} _ID. E.g. Student_ID property
of Student entity will be primary key:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder
.Properties()
.Where(p => p.Name == p.DeclaringType.Name + "_ID")
.Configure(p => p.IsKey());

base.OnModelCreating(modelBuilder);
}








Following example show how to set string length of Description property in all entities:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder
.Properties()
.Where(p => p.Name == "Description")
.Configure(p => p.HasMaxLength(200));

base.OnModelCreating(modelBuilder);
}
You can also define custom class for this convention by deriving Convention class as below:

public class PKConvention : Convention
{
public PKConvention()
{
.Properties()
.Where(p => p.Name == p.DeclaringType.Name + "_ID")
.Configure(p => p.IsKey());

}
}
Configure custom convention as below:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add<PKConvention>();
}
Model Conventions:

Model Conventions is based on the underlying model metadata. There are conventions for CSDL and SSDL both.
Create class that implements IConceptualModelConvention form CSDL conventions and implement
IStoreModelConvention for SSDL convention.

Visit codeplex documentation for more information.

Download code-first sample project for custom conventions demo.
























9. Code First - Insert, Update, Delete Stored Procedure Mapping:
Entity Framework 6 Code First provides ability to create and use stored procedure for add, update and delete operation.
It was not possible in the previous versions of Entity Framework.

Student Entity:

class Student
{
public Student()
{
}

public int Student_ID { get; set; }
public string StudentName { get; set; }
}
Following example automatically create stored procedure for Student entity using Fluent API.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.MapToStoredProcedures();
}
Above code will create three procedures Student_Insert, Student_Update and Student_Delete. Student_Insert and
Student_Update stored procedures has parameters name corresponds to the property names. Student_Delete will have
primary key property StudentID parameter.

You can also change stored procedure and parameters name as below:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.MapToStoredProcedures(p => p.Insert(sp =>
sp.HasName("sp_InsertStudent").Parameter(pm => pm.StudentName, "name").Result(rs =>
rs.Student_ID, "Student_ID"))
.Update(sp => sp.HasName("sp_UpdateStudent").Parameter(pm => pm.StudentName,
"name"))
.Delete(sp => sp.HasName("sp_DeleteStudent").Parameter(pm => pm.Student_ID, "Id"))
);
}
If you want all your entities to use stored procedures then do as following:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Types().Configure(t => t.MapToStoredProcedures());
}

Limitations:

Only Fluent API can be used to map stored procedures. You cannot use Data Annotation attributes in EF 6 for
stored procedure mapping.
You cannot use mixture of stored procedure and query to add, update and delete operation on the same entity.
You can either use stored procedure or SQL query for all add, update and delete operation with entity.

Download sample project for demo.


10. Index Attribute:
Entity Framework 6 provides Index attribute to create Index on particular column in the database as below:

class Student
{
public Student()
{
}

public int Student_ID { get; set; }
public string StudentName { get; set; }

[Index]
public int RegistrationNumber { get; set; }
}
By default, Index name will be IX_{property name}. However, you can also change Index name.

You can also make it Clustered index by specifying IsClustered = true and unique index by specifying IsUnique=true.

[Index( "INDEX_REGNUM", IsClustered=true, IsUnique=true )]
public int RegistrationNumber { get; set; }
Download Code-First sample project for Index attribute demo.


PREVIOUS
NEXT
11. Download Sample Project:
Download sample project for Entity Framework 6 Code-First model below.



Download sample project for Entity Framework 6 Database-First below.



Above sample projects already includes SchoolDB.mdf file required for the sample project. So attach SchoolDB.mdf to
your MS SQL Server database before running sample projects.






















Glossary

Term Definition
Code First Creating an Entity Framework model using code. The model can target and existing database or a new database.
Context
A class that represents a session with the database, allowing you to query and save data. A context derives from
the DbContext or ObjectContext class.
Convention (Code
First)
A rule that Entity Framework uses to infer the shape of you model from your classes.
Database First Creating an Entity Framework model, using the EF Designer, that targets an existing database.
Eager loading
A pattern of loading related data where a query for one type of entity also loads related entities as part of the
query.
EF Designer A visual designer in Visual Studio that allows you to create an Entity Framework model using boxes and lines.
Entity A class or object that represents application data such as customers, products, and orders.
Entity Data Model A model that describes entities and the relationships between them.
Explicit loading A pattern of loading related data where related objects are loaded by calling an API.
Fluent API An API that can be used to configure a Code First model.
Foreign key
association
An association between entities where a property that represents the foreign key is included in the class of the
dependent entity (i.e. the Product contains a CategoryId property).
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.
Independent
association
An association between entities where there is no property representing the foreign key in the class of the
dependent entity (i.e. a Product class contains a relationship to Category but no CategoryId property). Entity
Framework will use an independent object to track this relationship.
Lazy loading
A pattern of loading related data where related objects are automatically loaded when a navigation property is
accessed.
Model First Creating an Entity Framework model, using the EF Designer, that is then used to create a new database.
Navigation
property
A property of an entity that references another entity (i.e. Product contains a Category navigation property and
Category contains a Products navigation property).
Relationship
inverse
The opposite end of a relationship, for example, product.Category and category.Product.
Self-tracking
entity
An entity built from a code generation template that helps with N-Tier development.
Table-per-concrete
type (TPC)
A method of mapping the inheritance where each non-abstract type in the hierarchy is mapped to separate table
in the database.
Table-per-
hierarchy (TPH)
A method of mapping the inheritance where all types in the hierarchy are mapped to the same table in the
database. A discriminator column(s) is used to identify what type each row is associated with.
Table-per-type
(TPT)
A method of mapping the inheritance where the common properties of all types in the hierarchy are mapped to
the same table in the database, but properties unique to each type are mapped to a separate table.
Type discovery The process of identifying the types that should be part of an Entity Framework model.

















Entity Framework Terminology
Term Definition
association The definition of a relationship between entity types.
For more information, see Association Element (CSDL) and association type.
association set A logical container for instances of associations of the same type.
For more information, see AssociationSet Element (CSDL) and association set.
Code First Starting with the Entity Framework 4.1 you can create a model programmatically
using Code First development. There are two different scenarios for Code First
development. In both cases, the developer defines a model by coding .NET
Framework class definitions, and then optionally specifies additional mapping or
configuration by using Data Annotations or the fluent API.
Note, that Code First development is part of the Entity Framework 5.0. The Entity
Framework 5.0 is not part of the .NET Framework, but is built on .NET Framework
4.5. The Entity Framework 5.0 is available as the Entity FrameworkNuGetpackage.
For more information, see Entity Framework Releases and Versioning.
command tree A common, programmatic representation of all Entity Framework queries that are
composed of one or more expressions.
For more information, see Entity Framework Overview.
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.
ComplexType The specification for a data type that represents a non-scalar property of an entity
type that does not have a key property.
For more information, see ComplexType Element (CSDL) and complex type.
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.
For more information, see Modeling and Mapping.
.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.
For more information, see EntityContainer Element (CSDL) and entity container.
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 or ReferentialConstraint element in a schema.
For more information, see NavigationProperty Element (CSDL) and navigation
property.
eager loading The process of loading a specific set of related objects along with the objects that
were explicitly requested in the query.
.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.
end A participating entity in an association.
For more information, see End Element (CSDL) and association end.
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.
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 asSqlClient.
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.
For more information, see EntityContainer Element (CSDL) and entity container.
Entity Data Model
(EDM)
A set of concepts that describe the structure of data, as entities and relationships,
regardless of its stored form.
For more information, see Entity Data Model.
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.
For more information, see EntitySet Element (CSDL) and entity set.
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 Working with Objects.
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.
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.
foreign key
association
An association between entities that is managed through foreign key properties.
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.
independent
association
An association between entities that is represented and tracked by an independent
object.
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.
For more information, see Key Element (CSDL) and entity key.
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.
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 in a storage model.
For more information, see MSL Specification.
.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.
For more information, see MSL Specification.
modification
functions
Stored procedures that are used to insert, update, and delete data that is in the
data source. These functions are used in place of Entity Framework generated
commands. Modification functions are defined by the Function element in the
storage model. The ModificationFunctionMapping element maps these
modification functions to insert, update, and delete operations against entities that
are defined in the conceptual model.
multiplicity The number of entities that can exist on each side of a relationship, as defined by
an association. Also known as cardinality.
For more information, see End Element (CSDL) and association end.
multiple entity sets
per type
The ability for an entity type to be defined in more than one entity set.
For more information, see EntitySet Element (CSDL) and How to: Define a Model
with Multiple Entity Sets per Type.
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.
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 Shaping Query Results (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 cont ext is represented by an instance of
the ObjectContext or DbContext class.
DbContext is part of the Entity Framework 5.0. The Entity Framework 5.0 is not part
of the .NET Framework, but is built on .NET Framework 4.5. The Entity Framework
5.0 is available as the Entity FrameworkNuGet package. For more information,
see Entity Framework Releases and Versioning.
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.
For more information, see Modeling and Mapping.
Object Services Services provided by the Entity Framework that enable application code to operate
on entities like .NET Framework objects.
persistence-
ignorant object
An object that does not contain any logic that is related to data storage. Also
known as a POCO entity.
POCO Plain Old CLR Object. An object that does not inherit from another class or
implement an interface.
POCO entity An entity in the Entity Framework that does not inherit
from EntityObject or ComplexObject and does not implement the Entity Framework
interfaces. Frequently, POCO entities are existing domain objects that you use in an
Entity Framework application. These entities support persistence ignorance. For
more information, see Working with POCO Entities.
proxy object An object that derives from a POCO class and is generated by the Entity Framework
to support change tracking and lazy loading. For more information,
see Requirements for Creating POCO Entities with Proxies.
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.
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.
scalar property A property of an entity that maps to a single field in the storage model.
self-tracking entity An entity built from a Text Template Transformation Toolkit (T4) that has the ability
to record changes to scalar, complex, and navigation properties.
simple type A primitive type that is used for defining properties in the conceptual model.
For more information, see Conceptual Model Types (CSDL) and Entity Data Model:
Primitive Data Types.
split entity An entity type that is mapped to two separate types in the storage model.
For more information, see How to: Define a Model with Single Entity Mapped to
Two Tables.
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 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.
table-per-hierarchy A method of modeling a type hierarchy in a database that includes the attributes of
all the types in the hierarchy in one table.
table-per-type A method of modeling a type hierarchy in a database that uses multiple tables with


one-to-one relationships to model the various types.