You are on page 1of 225

8/12/2016

EntityFrameworkQuickGuide

ENTITYFRAMEWORKQUICKGUIDE
http://www.tutorialspoint.com/entity_framework/entity_framework_quick_guide.htm

Copyrighttutorialspoint.com

ENTITYFRAMEWORKOVERVIEW
WhatisEntityFramework?
EntityFrameworkwasfirstreleasedin2008,Microsoft'sprimarymeansofinteractingbetween.NET
applicationsandrelationaldatabases.EntityFrameworkisanObjectRelationalMapperORM whichisatypeof
toolthatsimplifiesmappingbetweenobjectsinyoursoftwaretothetablesandcolumnsofarelational
database.
EntityFrameworkEF isanopensourceORMframeworkforADO.NETwhichisapartof.NET
Framework.
AnORMtakescareofcreatingdatabaseconnectionsandexecutingcommands,aswellastakingquery
resultsandautomaticallymaterializingthoseresultsasyourapplicationobjects.
AnORMalsohelpstokeeptrackofchangestothoseobjects,andwheninstructed,itwillalsopersist
thosechangesbacktothedatabaseforyou.

WhyEntityFramework?
EntityFrameworkisanORMandORMsareaimedtoincreasethedevelopersproductivitybyreducingthe
redundanttaskofpersistingthedatausedintheapplications.
EntityFrameworkcangeneratethenecessarydatabasecommandsforreadingorwritingdatainthe
databaseandexecutethemforyou.
Ifyou'requerying,youcanexpressyourqueriesagainstyourdomainobjectsusingLINQtoentities.
EntityFrameworkwillexecutetherelevantqueryinthedatabaseandthenmaterializeresultsinto
instancesofyourdomainobjectsforyoutoworkwithinyourapp.
ThereareotherORMsinthemarketplacesuchasNHibernateandLLBLGenPro.MostORMstypicallymap
domaintypesdirectlytothedatabaseschema.

EntityFrameworkhasamoregranularmappinglayersoyoucancustomizemappings,forexample,bymapping
thesingleentitytomultipledatabasetablesorevenmultipleentitiestoasingletable.

http://www.tutorialspoint.com/cgibin/printpage.cgi

1/225

8/12/2016

EntityFrameworkQuickGuide

EntityFrameworkisMicrosoft'srecommendeddataaccesstechnologyfornewapplications.
ADO.NETseemstoreferdirectlytothetechnologyfordatasetsanddatatables.
EntityFrameworkiswherealloftheforwardmovinginvestmentisbeingmade,whichhasbeenthecase
foranumberofyearsalready.
MicrosoftrecommendsthatyouuseEntityFrameworkoverADO.NETorLINQtoSQLforallnew
development.

ConceptualModel
Fordeveloperswhoareusedtodatabasefocuseddevelopment,thebiggestshiftwithEntityFrameworkisthatit
letsyoufocusonyourbusinessdomain.Whatitisthatyouwantyourapplicationtodowithoutbeinglimitedby
whatthedatabaseisabletodo?
WithEntityFramework,thefocalpointisreferredtoasaconceptualmodel.It'samodeloftheobjectsin
yourapplication,notamodelofthedatabaseyouusetopersistyourapplicationdata.
Yourconceptualmodelmayhappentoalignwithyourdatabaseschemaoritmaybequitedifferent.
YoucanuseaVisualDesignertodefineyourconceptualmodel,whichcanthengeneratetheclassesyou
willultimatelyuseinyourapplication.
YoucanjustdefineyourclassesanduseafeatureofEntityFrameworkcalledCodeFirst.AndthenEntity
Frameworkwillcomprehendtheconceptualmodel.

Eitherway,EntityFrameworkworksouthowtomovefromyourconceptualmodeltoyourdatabase.So,you
canqueryagainstyourconceptualmodelobjectsandworkdirectlywiththem.

Features

http://www.tutorialspoint.com/cgibin/printpage.cgi

2/225

8/12/2016

EntityFrameworkQuickGuide

FollowingarethebasicfeaturesofEntityFramework.Thislistiscreatedbasedonthemostnotablefeaturesand
alsofromfrequentlyaskedquestionsaboutEntityFramework.
EntityFrameworkisaMicrosofttool.
EntityFrameworkisbeingdevelopedasanOpenSourceproduct.
EntityFrameworkisnolongertiedordependenttothe.NETreleasecycle.
WorkswithanyrelationaldatabasewithvalidEntityFrameworkprovider.
SQLcommandgenerationfromLINQtoEntities.
EntityFrameworkwillcreateparameterizedqueries.
Trackschangestoinmemoryobjects.
Allowstoinsert,updateanddeletecommandgeneration.
Workswithavisualmodelorwithyourownclasses.
EntityFrameworkhasstoredProcedureSupport.

ENTITYFRAMEWORKARCHITECTURE
ThearchitectureofEntityFramework,fromthebottomup,consistsofthefollowing

DataProviders
Thesearesourcespecificproviders,whichabstracttheADO.NETinterfacestoconnecttothedatabasewhen
programmingagainsttheconceptualschema.
IttranslatesthecommonSQLlanguagessuchasLINQviacommandtreetonativeSQLexpressionandexecutes
itagainstthespecificDBMSsystem.

EntityClient
Thislayerexposestheentitylayertotheupperlayer.Entityclientprovidestheabilityfordeveloperstowork
againstentitiesintheformofrowsandcolumnsusingentitySQLquerieswithouttheneedtogenerateclassesto
representconceptualschema.EntityClientshowstheentityframeworklayers,whicharethecorefunctionality.
TheselayersarecalledasEntityDataModel.

http://www.tutorialspoint.com/cgibin/printpage.cgi

3/225

8/12/2016

EntityFrameworkQuickGuide

TheStorageLayercontainstheentiredatabaseschemainXMLformat.
TheEntityLayerwhichisalsoanXMLfiledefinestheentitiesandrelationships.
TheMappinglayerisanXMLfilethatmapstheentitiesandrelationshipsdefinedatconceptuallayer
withactualrelationshipsandtablesdefinedatlogicallayer.
TheMetadataserviceswhichisalsorepresentedinEntityClientprovidescentralizedAPItoaccess
metadatastoredEntity,MappingandStoragelayers.

ObjectService
ObjectServiceslayeristheObjectContext,whichrepresentsthesessionofinteractionbetweentheapplications
andthedatasource.
ThemainuseoftheObjectContextistoperformdifferentoperationslikeadd,deleteinstancesofentities
andtosavethechangedstatebacktothedatabasewiththehelpofqueries.
ItistheORMlayerofEntityFramework,whichrepresentsthedataresulttotheobjectinstancesof
entities.
ThisservicesallowdevelopertousesomeoftherichORMfeatureslikeprimarykeymapping,change
tracking,etc.bywritingqueriesusingLINQandEntitySQL.

ENTITYFRAMEWORKENVIRONMENTSETUP
WhatsNewinEntityFramework6?
FrameworkhasacomplexAPIthatletsyouhavegranularcontrolovereverythingfromitsmodelingtoits
runtimebehavior.PartofEntityFramework5livesinsideof.NET.Andanotherpartofitlivesinsideofan
additionalassemblythat'sdistributedusingNuGet.
ThecorefunctionalityofEntityFrameworkisbuiltintothe.NETFramework.

http://www.tutorialspoint.com/cgibin/printpage.cgi

4/225

8/12/2016

EntityFrameworkQuickGuide

TheCodeFirstsupport,that'swhatletsEntityFrameworkuseclassesinlieuofavisualmodel,anda
lighterwayAPIforinteractingwithEFareintheNuGetpackage.
Thecoreiswhatprovidesthequerying,changetrackingandallofthetransformationfromyourqueries
toSQLqueriesaswellasfromdatareturnintotheobjects.
YoucanusetheEF5NuGetpackagewithboth.NET4andwith.NET4.5.
Onebigpointofconfusion.NET4.5addedsupportforenumsandspatialdatatothecoreEntity
FrameworkAPIs,whichmeansifyou'reusingEF5with.NET4,youwon'tgetthesenewfeatures.You'll
onlygetthemwhencombiningEF5with.NET4.5.

LetusnowtakealookatEntityFramework6.ThecoreAPIswhichwereinsideof.NETinEntityFramework6
arenowapartofNuGetpackage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

5/225

8/12/2016

EntityFrameworkQuickGuide

Itmeans
AlloftheEntityFrameworklivesinsidesthisassemblythat'sdistributedbyNuGet
Youwon'tbedependenton.NETtoprovidespecificfeaturesliketheEntityFrameworkenumsupport
andspecialdatasupport.
You'llseethatoneofthefeaturesofEF6isthatitsupportsenumsandspatialdatafor.NET4
TostartworkingonEntityFrameworkyouneedtoinstallthefollowingdevelopmenttools
VisualStudio2013orabove
SQLServer2012orabove
EntityFrameworkupdatesfromNuGetPackage
MicrosoftprovidesafreeversionofvisualstudiowhichalsocontainsSQLServeranditcanbedownloaded
fromwww.visualstudio.com.

Installation
Step1Oncedownloadingiscomplete,runtheinstaller.Thefollowingdialogwillbedisplayed.

http://www.tutorialspoint.com/cgibin/printpage.cgi

6/225

8/12/2016

EntityFrameworkQuickGuide

Step2ClickontheInstallbuttonanditwillstarttheinstallationprocess.

Step3Oncetheinstallationprocessiscompletedsuccessfully,youwillseethefollowingdialog.Closethis
dialogandrestartyourcomputerifrequired.

http://www.tutorialspoint.com/cgibin/printpage.cgi

7/225

8/12/2016

EntityFrameworkQuickGuide

Step4OpenVisualStudiofromstartMenuwhichwillopenthefollowingdialog.Itwillbeawhileforthefirst
timeforpreparation.

Step5OnceallisdoneyouwillseethemainwindowofVisualstudio.

http://www.tutorialspoint.com/cgibin/printpage.cgi

8/225

8/12/2016

EntityFrameworkQuickGuide

LetscreateanewprojectfromFileNewProject

http://www.tutorialspoint.com/cgibin/printpage.cgi

9/225

8/12/2016

EntityFrameworkQuickGuide

Step1SelectConsoleApplicationandclickOKbutton.
Step2InsolutionExplorer,rightclickonyourproject.

Step3SelectManageNuGetPackagesasshownintheaboveimage,whichwillopenthefollowingwindowin
VisualStudio.

http://www.tutorialspoint.com/cgibin/printpage.cgi

10/225

8/12/2016

EntityFrameworkQuickGuide

Step4SearchforEntityFrameworkandinstallthelatestversionbypressingtheinstallbutton.

http://www.tutorialspoint.com/cgibin/printpage.cgi

11/225

8/12/2016

EntityFrameworkQuickGuide

Step5ClickOk.Onceinstallationisdone,youwillseethefollowingmessageinyouroutputWindow.

http://www.tutorialspoint.com/cgibin/printpage.cgi

12/225

8/12/2016

EntityFrameworkQuickGuide

Youarenowreadytostartyourapplication.

ENTITYFRAMEWORKDATABASESETUP
Inthistutorial,wewillbeusingasimpleUniversitydatabase.AUniversitydatabasecanbemuchmorecomplex
asawholebutfordemoandlearningpurpose,weareusingthesimplestformofthisdatabase.Thefollowing
diagramcontainsthreetables.
Student
Course
Enrollment

http://www.tutorialspoint.com/cgibin/printpage.cgi

13/225

8/12/2016

EntityFrameworkQuickGuide

Wheneveratermdatabaseisusedonethingcomesdirectlytoourmindandthatisdifferentkindoftableswhich
hassomesortofrelationship.Therearethreetypesofrelationshipsbetweentablesandtherelationship
betweendifferenttablesdependsonhowtherelatedcolumnsaredefined.
OnetoManyRelationship
ManytoManyRelationship
OnetoOneRelationship

OnetoManyRelationship
Onetomanyrelationshipisthemostcommontypeofrelationship.Inthistypeofrelationship,arowintableA
canhavemanymatchingrowsintableB,butarowintableBcanhaveonlyonematchingrowintableA.For
example,intheabovediagram,StudentandEnrollmenttablehaveonetomanyrelationship,eachstudentmay
havemanyenrollments,buteachenrollmentbelongstoonlyonestudent.

ManytoManyRelationship
Inamanytomanyrelationship,arowintableAcanhavemanymatchingrowsintableB,andviceversa.You
createsucharelationshipbydefiningathirdtable,calledajunctiontable,whoseprimarykeyconsistsofthe
foreignkeysfrombothtableAandtableB.Forexample,StudentandCoursetablehavemanytomany
relationshipthatisdefinedbyaonetomanyrelationshipfromeachofthesetablestotheEnrollmenttable.

OnetoOneRelationship
Inonetoonerelationship,arowintableAcanhavenomorethanonematchingrowintableB,andviceversa.
Aonetoonerelationshipiscreatedifbothoftherelatedcolumnsareprimarykeysorhaveuniqueconstraints.
Thistypeofrelationshipisnotcommonbecausemostinformationrelatedinthiswaywouldbeallinonetable.
Youmightuseaonetoonerelationshipto
Divideatablewithmanycolumns.
Isolatepartofatableforsecurityreasons.
Storedatathatisshortlivedandcouldbeeasilydeletedbysimplydeletingthetable.
Storeinformationthatappliesonlytoasubsetofthemaintable.

ENTITYFRAMEWORKDATAMODEL
TheEntityDataModelEDM isanextendedversionoftheEntityRelationshipmodelwhichspecifiesthe
conceptualmodelofthedatausingvariousmodellingtechnique.Italsoreferstoasetofconceptsthatdescribe

http://www.tutorialspoint.com/cgibin/printpage.cgi

14/225

8/12/2016

EntityFrameworkQuickGuide

datastructure,regardlessofitsstoredform.
EDMsupportsasetofprimitivedatatypesthatdefinepropertiesinaconceptualmodel.Weneedtoconsider3
corepartswhichformthebasisforEntityFrameworkandcollectivelyitisknownasEntityDataModel.
FollowingarethethreecorepartsofEDM.
TheStorageSchemaModel
TheConceptualModel
TheMappingModel

TheStorageSchemaModel
TheStorageModelalsocalledasStorageSchemaDefinitionLayerS S DLrepresentstheschematic
representationofthebackenddatastore.

TheConceptualModel
TheConceptualModelalsocalledasConceptualSchemaDefinitionLayerC S DL istherealentitymodel,
againstwhichwewriteourqueries.

TheMappingModel
MappingLayerisjustamappingbetweentheConceptualmodelandtheStoragemodel.
ThelogicalschemaanditsmappingwiththephysicalschemaisrepresentedasanEDM.
VisualStudioalsoprovidesEntityDesigner,forvisualcreationoftheEDMandthemapping
specification.
TheoutputofthetoolistheXMLfile. edmx specifyingtheschemaandthemapping.
EdmxfilecontainsEntityFrameworkmetadataartifacts.

SchemaDefinitionLanguage
ADO.NETEntityFrameworkusesanXMLbasedDataDefinitionLanguagecalledSchemaDefinitionLanguage
S DLtodefinetheEDMSchema.
TheSDLdefinestheSimpleTypessimilartootherprimitivetypes,includingString,Int32,Double,
Decimal,andDateTime,amongothers.
AnEnumeration,whichdefinesamapofprimitivevaluesandnames,isalsoconsideredasimpletype.
Enumerationsaresupportedfromframeworkversion5.0onwardsonly.
ComplexTypesarecreatedfromanaggregationofothertypes.Acollectionofpropertiesofthesetypes
defineanEntityType.

http://www.tutorialspoint.com/cgibin/printpage.cgi

15/225

8/12/2016

EntityFrameworkQuickGuide

Thedatamodelprimarilyhasthreekeyconceptstodescribedatastructure
Entitytype
Associationtype
Property

EntityType
TheentitytypeisthefundamentalbuildingblockfordescribingthestructureofdatainEDM.
Inaconceptualmodel,entitytypesareconstructedfrompropertiesanddescribethestructureoftop
levelconcepts,suchasaStudentsandEnrollmentsinabusinessapplication.
AnentityrepresentsaspecificobjectsuchasaspecificStudentorEnrollment.
Eachentitymusthaveauniqueentitykeywithinanentityset.Anentitysetisacollectionofinstancesofa
specificentitytype.Entitysetsandassociationsetsarelogicallygroupedinanentitycontainer.
Inheritanceissupportedwithentitytypes,thatis,oneentitytypecanbederivedfromanother.

AssociationType
ItisanotherfundamentalbuildingblockfordescribingrelationshipsinEDM.Inaconceptualmodel,an
associationrepresentsarelationshipbetweentwoentitytypessuchasStudentandEnrollment.
Everyassociationhastwoassociationendsthatspecifytheentitytypesinvolvedintheassociation.
Eachassociationendalsospecifiesanassociationendmultiplicitythatindicatesthenumberofentities
thatcanbeatthatendoftheassociation.
Anassociationendmultiplicitycanhaveavalueofone1,zeroorone0..1 ,ormany.
Entitiesatoneendofanassociationcanbeaccessedthroughnavigationproperties,orthroughforeign
keysiftheyareexposedonanentitytype.

Property
Entitytypescontainpropertiesthatdefinetheirstructureandcharacteristics.Forexample,aStudententity
typemayhavepropertiessuchasStudentId,Nameetc.
Apropertycancontainprimitivedatasuchasastring, aninteger, oraBooleanvalue ,orstructureddata
suchasacomplextype .

ENTITYFRAMEWORKDBCONTEXT

http://www.tutorialspoint.com/cgibin/printpage.cgi

16/225

8/12/2016

EntityFrameworkQuickGuide

ENTITYFRAMEWORKDBCONTEXT
TheEntityFrameworkenablesyoutoquery,insert,update,anddeletedata,usingCommonLanguageRuntime
C LR objectswhichisknownasentities.TheEntityFrameworkmapstheentitiesandrelationshipsthatare
definedinyourmodeltoadatabase.Italsoprovidesfacilitiesto
Materializedatareturnedfromthedatabaseasentityobjects
Trackchangesthatweremadetotheobjects
Handleconcurrency
Propagateobjectchangesbacktothedatabase
Bindobjectstocontrols
TheprimaryclassthatisresponsibleforinteractingwithdataasobjectsisSystem.Data.Entity.DbContext.The
DbContextAPIisnotreleasedaspartofthe.NETFramework.Inordertobemoreflexibleandfrequentwith
releasingnewfeaturestoCodeFirstandtheDbContextAPI,theEntityFrameworkteamdistributes
EntityFramework.dllthroughMicrosoftsNuGetdistributionfeature.
NuGetallowsyoutoaddreferencestoyour.NETprojectsbypullingtherelevantDLLsdirectlyintoyour
projectfromtheWeb.
AVisualStudioextensioncalledtheLibraryPackageManagerprovidesaneasywaytopullthe
appropriateassemblyfromtheWebintoyourprojects.

DbContextAPIismostlytargetedatsimplifyingyourinteractionwithEntityFramework.
Italsoreducesthenumberofmethodsandpropertiesyouneedtoaccesscommonlyusedtasks.
InpreviousversionsofEntityFramework,thesetaskswereoftencomplicatedtodiscoverandcode.

http://www.tutorialspoint.com/cgibin/printpage.cgi

17/225

8/12/2016

EntityFrameworkQuickGuide

Thecontextclassmanagestheentityobjectsduringruntime,whichincludespopulatingobjectswithdata
fromadatabase,changetracking,andpersistingdatatothedatabase.

DefiningaDbContextDerivedClass
TherecommendedwaytoworkwithcontextistodefineaclassthatderivesfromDbContextandexposesDbSet
propertiesthatrepresentcollectionsofthespecifiedentitiesinthecontext.IfyouareworkingwiththeEF
Designer,thecontextwillbegeneratedforyou.IfyouareworkingwithCodeFirst,youwilltypicallywritethe
contextyourself.
ThefollowingcodeisasimpleexamplewhichshowsthatUniContextisderivedfromDbContext.
YoucanuseautomaticpropertieswithDbSetsuchasgetterandsetter.
Italsomakesmuchcleanercode,butyouarentrequiredtouseitforthepurposeofcreatingaDbSet
whenyouhavenootherlogictoapply.
publicclassUniContext:DbContext{
publicUniContext():base("UniContext"){}
publicDbSet<Student>Students{get;set;}
publicDbSet<Enrollment>Enrollments{get;set;}
publicDbSet<Course>Courses{get;set;}
}

Previously,EDMusedtogeneratecontextclassesthatwerederivedfromtheObjectContextclass.
WorkingwithObjectContextwasalittlecomplex.
DbContextisawrapperaroundObjectContextwhichisactuallysimilartoObjectContextandisusefuland
easyinallthedevelopmentmodelssuchCodeFirst,ModelFirstandDatabaseFirst.

Queries
Therearethreetypesofqueriesyoucanusesuchas
Addinganewentity.
Changingorupdatingthepropertyvaluesofanexistingentity.
Deletinganexistingentity.

AddingNewEntities
AddinganewobjectwithEntityFrameworkisassimpleasconstructinganewinstanceofyourobjectand
registeringitusingtheAddmethodonDbSet.Thefollowingcodeisforwhenyouwanttoaddanewstudentto
database.
privatestaticvoidAddStudent(){
using(varcontext=newUniContext()){
varstudent=newStudent{
LastName="Khan",
FirstMidName="Ali",
EnrollmentDate=DateTime.Parse("20050901")
};
context.Students.Add(student);
context.SaveChanges();

http://www.tutorialspoint.com/cgibin/printpage.cgi

18/225

8/12/2016

EntityFrameworkQuickGuide

}
}

ChangingExistingEntities
Changingexistingobjectsisassimpleasupdatingthevalueassignedtothepropertysyouwantchangedand
callingSaveChanges.Inthefollowingcode,thelastnameofAlihasbeenchangedfromKhantoAslam.
privatestaticvoidAddStudent(){
privatestaticvoidChangeStudent(){
using(varcontext=newUniContext()){
varstudent=(fromdincontext.Students
whered.FirstMidName=="Ali"selectd).Single();
student.LastName="Aslam";
context.SaveChanges();
}
}
}

DeletingExistingEntities
TodeleteanentityusingEntityFramework,youusetheRemovemethodonDbSet.Removeworksforboth
existingandnewlyaddedentities.CallingRemoveonanentitythathasbeenaddedbutnotyetsavedtothe
databasewillcanceltheadditionoftheentity.Theentityisremovedfromthechangetrackerandisnolonger
trackedbytheDbContext.CallingRemoveonanexistingentitythatisbeingchangetrackedwillregisterthe
entityfordeletionthenexttimeSaveChangesiscalled.Thefollowingexampleshowsaninstancewherethe
studentisremovedfromthedatabasewhosefirstnameisAli.
privatestaticvoidDeleteStudent(){
using(varcontext=newUniContext()){
varbay=(fromdincontext.Studentswhered.FirstMidName=="Ali"selectd).Single();
context.Students.Remove(bay);
context.SaveChanges();
}
}

ENTITYFRAMEWORKTYPES
InEntityFramework,therearetwotypesofentitiesthatallowdeveloperstousetheirowncustomdataclasses
togetherwithdatamodelwithoutmakinganymodificationstothedataclassesthemselves.
POCOentities
DynamicProxy

POCOEntities
POCOstandsfor"plainold"CLRobjectswhichcanbeusedasexistingdomainobjectswithyourdata
model.
POCOdataclasseswhicharemappedtoentitiesaredefinedinadatamodel.
Italsosupportsmostofthesamequery,insert,update,anddeletebehaviorsasentitytypesthatare
generatedbytheEntityDataModeltools.

http://www.tutorialspoint.com/cgibin/printpage.cgi

19/225

8/12/2016

EntityFrameworkQuickGuide

YoucanusethePOCOtemplatetogeneratepersistenceignorantentitytypesfromaconceptualmodel.
LetstakealookatthefollowingexampleofConceptualEntityDataModel.

TogeneratePOCOentitiesfortheaboveEntitymodel
Step1Rightclickonthedesignerwindow.Itwilldisplaythefollowingdialog.

http://www.tutorialspoint.com/cgibin/printpage.cgi

20/225

8/12/2016

EntityFrameworkQuickGuide

Step2SelecttheAddCodeGenerationItem...

http://www.tutorialspoint.com/cgibin/printpage.cgi

21/225

8/12/2016

EntityFrameworkQuickGuide

Step3SelecttheEF6.xDbContextGenerator,writenameandthenclickAddbutton.
YouwillseeinyoursolutionexplorerthatPOCODemo.Context.ttandPOCODemo.tttemplatesaregenerated.

http://www.tutorialspoint.com/cgibin/printpage.cgi

22/225

8/12/2016

EntityFrameworkQuickGuide

ThePOCODemo.ContextgeneratestheDbContextandtheobjectsetsthatyoucanreturnanduseforquerying,
sayforcontext,StudentsandCourses,etc.

http://www.tutorialspoint.com/cgibin/printpage.cgi

23/225

8/12/2016

EntityFrameworkQuickGuide

TheothertemplatedealswithallthetypesStudent,Courses,etc.FollowingisthecodeforStudentclasswhichis
generatedautomaticallyfromtheEntityModel.
namespaceConsoleApplication1{
usingSystem;
usingSystem.Collections.Generic;
publicpartialclassStudent{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2214:DoNotCallOverridableMethodsInConstructors")]
publicStudent(){
this.Enrollments=newHashSet<Enrollment>();
}
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicSystem.DateTimeEnrollmentDate{get;set;}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
CA2227:CollectionPropertiesShouldBeReadOnly")]
publicvirtualICollection<Enrollment>Enrollments{get;set;}

http://www.tutorialspoint.com/cgibin/printpage.cgi

24/225

8/12/2016

EntityFrameworkQuickGuide

}
}

SimilarclassesaregeneratedforCourseandEnrollmenttablesfromtheEntityModel.

DynamicProxy
WhencreatinginstancesofPOCOentitytypes,theEntityFrameworkoftencreatesinstancesofadynamically
generatedderivedtypethatactsasaproxyfortheentity.ITcanalsobesaidthatitisaruntimeproxyclasses
likeawrapperclassofPOCOentity.
Youcanoverridesomepropertiesoftheentityforperformingactionsautomaticallywhenthepropertyis
accessed.
Thismechanismisusedtosupportlazyloadingofrelationshipsandautomaticchangetracking.
ThistechniquealsoappliestothosemodelswhicharecreatedwithCodeFirstandEFDesigner.
IfyouwanttheEntityFrameworktosupportlazyloadingoftherelatedobjectsandtotrackchangesinPOCO
classes,thenthePOCOclassesmustmeetthefollowingrequirements
Customdataclassmustbedeclaredwithpublicaccess.
Customdataclassmustnotbesealed.
Customdataclassmustnotbeabstract.
Customdataclassmusthaveapublicorprotectedconstructorthatdoesnothaveparameters.
UseaprotectedconstructorwithoutparametersifyouwanttheCreateObjectmethodtobeusedtocreate
aproxyforthePOCOentity.
CallingtheCreateObjectmethoddoesnotguaranteethecreationoftheproxy:thePOCOclassmust
followtheotherrequirementsthataredescribedinthistopic.
TheclasscannotimplementtheIEntityWithChangeTrackerorIEntityWithRelationshipsinterfaces
becausetheproxyclassesimplementtheseinterfaces.
TheProxyCreationEnabledoptionmustbesettotrue.
Thefollowingexampleisofdynamicproxyentityclass.
publicpartialclassCourse{
publicCourse(){
this.Enrollments=newHashSet<Enrollment>();
}
publicintCourseID{get;set;}
publicstringTitle{get;set;}
publicintCredits{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Todisablecreatingproxyobjects,setthevalueoftheProxyCreationEnabledpropertytofalse.

ENTITYFRAMEWORKRELATIONSHIPS

http://www.tutorialspoint.com/cgibin/printpage.cgi

25/225

8/12/2016

EntityFrameworkQuickGuide

Inrelationaldatabases,relationshipisasituationthatexistsbetweenrelationaldatabasetablesthroughforeign
keys.AForeignKeyF K isacolumnorcombinationofcolumnsthatisusedtoestablishandenforcealink
betweenthedataintwotables.Thefollowingdiagramcontainsthreetables.
Student
Course
Enrollment

Intheabovediagram,youcanseesomesortofassociation/relationshipbetweentables.Therearethreetypes
ofrelationshipsbetweentablesandtherelationshipbetweendifferenttablesdependsonhowtherelated
columnsaredefined.
OnetoManyRelationship
ManytoManyRelationship
OnetoOneRelationship

OnetoManyRelationship
Aonetomanyrelationshipisthemostcommontypeofrelationship.
Inthistypeofrelationship,arowintableAcanhavemanymatchingrowsintableB,butarowintableB
canhaveonlyonematchingrowintableA.
Theforeignkeyisdefinedinthetablethatrepresentsthemanyendoftherelationship.
Forexample,intheabovediagramStudentandEnrollmenttableshaveonetomanyrelationship,each
studentmayhavemanyenrollments,buteachenrollmentbelongstoonlyonestudent.
Inentityframework,theserelationshipcanbecreatedwithcodeaswell.FollowingisanexampleofStudentand
Enrollmentclasseswhichareassociatedwithonetomanyrelationship.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassEnrollment{
publicintEnrollmentID{get;set;}

http://www.tutorialspoint.com/cgibin/printpage.cgi

26/225

8/12/2016

EntityFrameworkQuickGuide

publicintCourseID{get;set;}
publicintStudentID{get;set;}

publicGrade?Grade{get;set;}
publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}

Intheabovecode,youcanseethatStudentclasscontainsthecollectionofEnrollment,butEnrollmentclasshas
asingleStudentObject.

ManytoManyRelationship
Inmanytomanyrelationship,arowintableAcanhavemanymatchingrowsintableB,andviceversa.
Youcancreatesucharelationshipbydefiningathirdtable,calledajunctiontable,whoseprimarykey
consistsoftheforeignkeysfrombothtableAandtableB.
Forexample,theStudentandCoursetableshavemanytomanyrelationshipthatisdefinedbyoneto
manyrelationshipfromeachofthesetablestotheEnrollmenttable.
ThefollowingcodecontainstheCourseclassandtheabovetwoclasses,i.e.,StudentandEnrollment.
publicclassCourse{
[DatabaseGenerated(DatabaseGeneratedOption.None)]

publicintCourseID{get;set;}
publicstringTitle{get;set;}

publicintCredits{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

YoucanseethatbothCourseclassandStudentclasshavecollectionsofEnrollmentobjectswhichmakesmany
tomanyrelationshipviajunctionclassEnrollment.

OnetoOneRelationship
Inaonetoonerelationship,arowintableAcanhavenomorethanonematchingrowintableB,andvice
versa.
Aonetoonerelationshipiscreatedifbothoftherelatedcolumnsareprimarykeysorhaveunique
constraints.
Inaonetoonerelationship,theprimarykeyactsadditionallyasaforeignkeyandthereisnoseparate
foreignkeycolumnforeithertable.
Thistypeofrelationshipisnotcommonbecausemostinformationrelatedinthiswaywouldbeallinonetable.
Youmightuseaonetoonerelationshipto
Divideatablewithmanycolumns.
Isolatepartofatableforsecurityreasons.
Storedatathatisshortlivedandcouldbeeasilydeletedbysimplydeletingthetable.
Storeinformationthatappliesonlytoasubsetofthemaintable.
ThefollowingcodeistoaddanotherclassnameStudentProfilewhichcontainsthestudentemailidand
password.

http://www.tutorialspoint.com/cgibin/printpage.cgi

27/225

8/12/2016

EntityFrameworkQuickGuide

publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
publicvirtualStudentProfileStudentProfile{get;set;}
}
publicclassStudentProfile{
publicStudentProfile(){}
publicintID{get;set;}
publicstringEmail{get;set;}
publicstringPassword{get;set;}

publicvirtualStudentStudent{get;set;}
}

YoucanseethatStudententityclasscontainsStudentProfilenavigationpropertyandStudentProfilecontains
Studentnavigationproperty.
EachstudenthasonlyoneEmailandpasswordtologininuniversitydomain.Theseinformationcanbeaddedto
Studenttablebutforsecurityreasonsitisseparatedtoanothertable.

ENTITYFRAMEWORKLIFECYCLE
Lifetime
Thelifetimeofacontextbeginswhentheinstanceiscreatedandendswhentheinstanceiseitherdisposedor
garbagecollected.
ContextlifetimeisaverycrucialdecisiontomakewhenweuseORMs.
Thecontextisperforminglikeanentitycache,soitmeansitholdsreferencestoalltheloadedentities
whichmaygrowveryfastinmemoryconsumptionanditcanalsocausememoryleaks.
Inthebelowdiagram,youcanseetheupperlevelofdataworkflowfromapplicationtodatabasevia
Contextandviceversa.

http://www.tutorialspoint.com/cgibin/printpage.cgi

28/225

8/12/2016

EntityFrameworkQuickGuide

EntityLifecycle
TheEntityLifecycledescribestheprocessinwhichanEntityiscreated,added,modified,deleted,etc.Entities
havemanystatesduringitslifetime.Beforelookingathowtoretrieveentitystate,letstakealookatwhatis
entitystate.ThestateisanenumoftypeSystem.Data.EntityStatethatdeclaresthefollowingvalues
Added:Theentityismarkedasadded.
Deleted:Theentityismarkedasdeleted.
Modified:Theentityhasbeenmodified.
Unchanged:Theentityhasntbeenmodified.
Detached:Theentityisnttracked.

StateChangesintheEntityLifecycle
Sometimesstateofentitiesaresetautomaticallybythecontext,butitcanalsobemodifiedmanuallybythe
developer.Eventhoughallthecombinationsofswitchesfromonestatetoanotherarepossible,butsomeof
themaremeaningless.Forexample,AddedentitytotheDeletedstate,orviceversa.

http://www.tutorialspoint.com/cgibin/printpage.cgi

29/225

8/12/2016

EntityFrameworkQuickGuide

Letsdiscussaboutdifferentstates.

UnchangedState
WhenanentityisUnchanged,itsboundtothecontextbutithasntbeenmodified.
Bydefault,anentityretrievedfromthedatabaseisinthisstate.
WhenanentityisattachedtothecontextwiththeAttachmethod ,itsimilarlyisintheUnchangedstate.
Thecontextcanttrackchangestoobjectsthatitdoesntreference,sowhentheyreattacheditassumes
theyreUnchanged.

DetachedState
Detachedisthedefaultstateofanewlycreatedentitybecausethecontextcanttrackthecreationofany
objectinyourcode.
Thisistrueevenifyouinstantiatetheentityinsideausingblockofthecontext.
Detachediseventhestateofentitiesretrievedfromthedatabasewhentrackingisdisabled.
Whenanentityisdetached,itisntboundtothecontext,soitsstateisnttracked.
Itcanbedisposedof,modified,usedincombinationwithotherclasses,orusedinanyotherwayyou
mightneed.
Becausethereisnocontexttrackingit,ithasnomeaningtoEntityFramework.

AddedState
WhenanentityisintheAddedstate,youhavefewoptions.Infact,youcanonlydetachitfromthe
context.
Naturally,evenifyoumodifysomeproperty,thestateremainsAdded,becausemovingittoModified,
Unchanged,orDeletedmakesnosense.
Itsanewentityandhasnocorrespondencewitharowinthedatabase.
Thisisafundamentalprerequisiteforbeinginoneofthosestatesbutthisruleisn tenf orcedbythecontext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

30/225

8/12/2016

EntityFrameworkQuickGuide

ModifiedState
Whenanentityismodified,thatmeansitwasinUnchangedstateandthensomepropertywaschanged.
AfteranentityenterstheModifiedstate,itcanmovetotheDetachedorDeletedstate,butitcantroll
backtotheUnchangedstateevenifyoumanuallyrestoretheoriginalvalues.
ItcantevenbechangedtoAdded,unlessyoudetachandaddtheentitytothecontext,becausearowwith
thisIDalreadyexistsinthedatabase,andyouwouldgetaruntimeexceptionwhenpersistingit.

DeletedState
AnentityenterstheDeletedstatebecauseitwasUnchangedorModifiedandthentheDeleteObject
methodwasused.
Thisisthemostrestrictivestate,becauseitspointlesschangingfromthisstatetoanyothervaluebut
Detached.
Theusingstatementifyouwantalltheresourcesthatthecontextcontrolstobedisposedattheendofthe
block.Whenyouusetheusingstatement,thencompilerautomaticallycreatesatry/finallyblockandcalls
disposeinthefinallyblock.
using(varcontext=newUniContext()){
varstudent=newStudent{
LastName="Khan",

http://www.tutorialspoint.com/cgibin/printpage.cgi

31/225

8/12/2016

EntityFrameworkQuickGuide

FirstMidName="Ali",
EnrollmentDate=DateTime.Parse("20050901")
};
context.Students.Add(student);
context.SaveChanges();
}

Whenworkingwithlongrunningcontextconsiderthefollowing
Asyouloadmoreobjectsandtheirreferencesintomemory,thememoryconsumptionofthecontextmay
increaserapidly.Thismaycauseperformanceissues.
Remembertodisposeofthecontextwhenitisnolongerrequired.
Ifanexceptioncausesthecontexttobeinanunrecoverablestate,thewholeapplicationmayterminate.
Thechancesofrunningintoconcurrencyrelatedissuesincreasesasthegapbetweenthetimewhenthe
dataisqueriedandupdatedgrows.
WhenworkingwithWebapplications,useacontextinstanceperrequest.
WhenworkingwithWindowsPresentationFoundationW P F orWindowsForms,useacontextinstance
perform.Thisletsyouusechangetrackingfunctionalitythatcontextprovides.

RulesofThumb
WebApplications
Itisnowacommonandbestpracticethatforwebapplications,contextisusedperrequest.
Inwebapplications,wedealwithrequeststhatareveryshortbutholdsalltheservertransactiontheyare
thereforetheproperdurationforthecontexttolivein.
DesktopApplications
Fordesktopapplication,likeWinForms/WPF,etc.thecontextisusedperform/dialog/page.
Sincewedontwanttohavethecontextasasingletonforourapplicationwewilldisposeitwhenwemove
fromoneformtoanother.
Inthisway,wewillgainalotofthecontextsabilitiesandwontsufferfromtheimplicationsoflong
runningcontexts.

ENTITYFRAMEWORKCODEFIRSTAPPROACH
TheEntityFrameworkprovidesthreeapproachestocreateanentitymodelandeachonehastheirownprosand
cons.
CodeFirst
DatabaseFirst
ModelFirst
Inthischapter,wewillbrieflydescribethecodefirstapproach.Somedevelopersprefertoworkwiththe
DesignerinCodewhileotherswouldratherjustworkwiththeircode.Forthosedevelopers,EntityFramework
hasamodelingworkflowreferredtoasCodeFirst.
CodeFirstmodelingworkflowtargetsadatabasethatdoesntexistandCodeFirstwillcreateit.

http://www.tutorialspoint.com/cgibin/printpage.cgi

32/225

8/12/2016

EntityFrameworkQuickGuide

ItcanalsobeusedifyouhaveanemptydatabaseandthenCodeFirstwilladdnewtablestoo.
CodeFirstallowsyoutodefineyourmodelusingC#orVB.Netclasses.
Additionalconfigurationcanoptionallybeperformedusingattributesonyourclassesandpropertiesor
byusingafluentAPI.

WhyCodeFirst?
CodeFirstisreallymadeupofasetofpuzzlepieces.Firstareyourdomainclasses.
ThedomainclasseshavenothingtodowithEntityFramework.They'rejusttheitemsofyourbusiness
domain.
EntityFramework,then,hasacontextthatmanagestheinteractionbetweenthoseclassesandyour
database.
ThecontextisnotspecifictoCodeFirst.It'sanEntityFrameworkfeature.
CodeFirstaddsamodelbuilderthatinspectsyourclassesthatthecontextismanaging,andthenusesa
setofrulesorconventionstodeterminehowthoseclassesandtherelationshipsdescribeamodel,and
howthatmodelshouldmaptoyourdatabase.

http://www.tutorialspoint.com/cgibin/printpage.cgi

33/225

8/12/2016

EntityFrameworkQuickGuide

Allofthishappensatruntime.You'llneverseethismodel,it'sjustinmemory.
CodeFirsthastheabilitytousethatmodeltocreateadatabaseifrequired.
Itcanalsoupdatethedatabaseifthemodelchanges,usingafeaturecalledCodeFirstMigrations.

ENTITYFRAMEWORKMODELFIRSTAPPROACH
Inthischapter,letuslearnhowtocreateanentitydatamodelinthedesignerusingtheworkflowreferredtoas
ModelFirst.
ModelFirstisgreatforwhenyou'restartinganewprojectwherethedatabasedoesn'tevenexistyet.
ThemodelisstoredinanEDMXfileandcanbeviewedandeditedintheEntityFrameworkDesigner.
InModelFirst,youdefineyourmodelinanEntityFrameworkdesignerthengenerateSQL,whichwill
createdatabaseschematomatchyourmodelandthenyouexecutetheSQLtocreatetheschemainyour
database.
TheclassesthatyouinteractwithinyourapplicationareautomaticallygeneratedfromtheEDMXfile.
FollowingisasimpleexampleofcreatinganewconsoleprojectusingModelFirstapproach.
Step1OpenVisualStudioandselectFileNewProject

Step2SelectInstalledTemplatesVisualC#Windowsfromleftpaneandtheninmiddlepane,select
ConsoleApplication.
Step3EnterEFModelFirstDemointheNamefield.
Step4Tocreatemodel,firstrightclickonyourconsoleprojectinsolutionexplorerandselectAddNew
Items

http://www.tutorialspoint.com/cgibin/printpage.cgi

34/225

8/12/2016

EntityFrameworkQuickGuide

Thefollowingdialogwillopen.

http://www.tutorialspoint.com/cgibin/printpage.cgi

35/225

8/12/2016

EntityFrameworkQuickGuide

Step5SelectADO.NETEntityDataModelfrommiddlepaneandenternameModelFirstDemoDBinthe
Namefield.
Step6ClickAddbuttonwhichwilllaunchtheEntityDataModelWizarddialog.

Step7SelectEmptyEFDesignermodelandclickNextbutton.TheEntityFrameworkDesigneropenswitha
blankmodel.Nowwecanstartaddingentities,propertiesandassociationstothemodel.
Step8RightclickonthedesignsurfaceandselectProperties.InthePropertieswindow,changetheEntity
ContainerNametoModelFirstDemoDBContext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

36/225

8/12/2016

EntityFrameworkQuickGuide

Step9RightclickonthedesignsurfaceandselectAddNewEntity

http://www.tutorialspoint.com/cgibin/printpage.cgi

37/225

8/12/2016

EntityFrameworkQuickGuide

AddEntitydialogwillopenasshowninthefollowingimage.

Step10EnterStudentasentitynameandStudentIdaspropertynameandclickOk.

http://www.tutorialspoint.com/cgibin/printpage.cgi

38/225

8/12/2016

EntityFrameworkQuickGuide

Step11RightclickonthenewentityonthedesignsurfaceandselectAddNewScalarProperty,enter
Nameasthenameoftheproperty.

Step12EnterFirstNameandthenaddanothertwoscalarpropertiessuchasLastNameandEnrollmentDate.

http://www.tutorialspoint.com/cgibin/printpage.cgi

39/225

8/12/2016

EntityFrameworkQuickGuide

Step13AddtwomoreEntitiesCourseandEnrollmentbyfollowingallthestepsmentionedaboveandalso
addsomeScalarpropertiesasshowninthefollowingsteps.

http://www.tutorialspoint.com/cgibin/printpage.cgi

40/225

8/12/2016

EntityFrameworkQuickGuide

Step14WehavethreeentitiesinVisualDesigner,letsaddsomeassociationorrelationshipbetweenthem.
Step15RightclickonthedesignsurfaceandselectAddNewAssociation

http://www.tutorialspoint.com/cgibin/printpage.cgi

41/225

8/12/2016

EntityFrameworkQuickGuide

Step16MakeoneendoftherelationshippointtoStudentwithamultiplicityofoneandtheotherendpoint
toEnrollmentwithamultiplicityofmany.

http://www.tutorialspoint.com/cgibin/printpage.cgi

42/225

8/12/2016

EntityFrameworkQuickGuide

Step17ThismeansthataStudenthasmanyEnrollmentsandEnrollmentbelongstooneStudent.
Step18EnsuretheAddforeignkeypropertiesto'Post'EntityboxischeckedandclickOK.
Step19Similarly,addonemoreassociationbetweenCourseandEnrollment.

http://www.tutorialspoint.com/cgibin/printpage.cgi

43/225

8/12/2016

EntityFrameworkQuickGuide

Step20Yourdatamodelwilllooklikethefollowingscreenafteraddingassociationsbetweenentities.

http://www.tutorialspoint.com/cgibin/printpage.cgi

44/225

8/12/2016

EntityFrameworkQuickGuide

Wenowhaveasimplemodelthatwecangenerateadatabasefromandusetoreadandwritedata.Let'sgo
aheadandgeneratethedatabase.
Step1RightclickonthedesignsurfaceandselectGenerateDatabasefromModel

http://www.tutorialspoint.com/cgibin/printpage.cgi

45/225

8/12/2016

EntityFrameworkQuickGuide

Step2YoucanselectexistingdatabaseorcreateanewconnectionbyclickingonNewConnection

http://www.tutorialspoint.com/cgibin/printpage.cgi

46/225

8/12/2016

EntityFrameworkQuickGuide

Step3TocreatenewDatabase,clickonNewConnection

http://www.tutorialspoint.com/cgibin/printpage.cgi

47/225

8/12/2016

EntityFrameworkQuickGuide

Step4EnterServernameanddatabasename.

http://www.tutorialspoint.com/cgibin/printpage.cgi

48/225

8/12/2016

EntityFrameworkQuickGuide

Step5ClickNext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

49/225

8/12/2016

EntityFrameworkQuickGuide

Step6ClickFinish.Thiswilladd*.edmx.sqlfileintheproject.YoucanexecuteDDLscriptsinVisualStudio
byopening.sqlfile,thenrightclickandselectExecute.

http://www.tutorialspoint.com/cgibin/printpage.cgi

50/225

8/12/2016

EntityFrameworkQuickGuide

Step7Thefollowingdialogwillbedisplayedtoconnecttodatabase.

Step8Onsuccessfulexecution,youwillseethefollowingmessage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

51/225

8/12/2016

EntityFrameworkQuickGuide

Step9Gototheserverexplorer,youwillseethatthedatabaseiscreatedwiththreetableswhichare
specified.

Next,weneedtoswapourmodeltogeneratecodethatmakesuseoftheDbContextAPI.

http://www.tutorialspoint.com/cgibin/printpage.cgi

52/225

8/12/2016

EntityFrameworkQuickGuide

Step1RightclickonanemptyspotofyourmodelintheEFDesignerandselectAddCodeGenerationItem

YouwillseethatthefollowingAddNewItemdialogopens.

http://www.tutorialspoint.com/cgibin/printpage.cgi

53/225

8/12/2016

EntityFrameworkQuickGuide

Step2SelectEF6.xDbContextGeneratorinmiddlepaneandenterModelFirstDemoModelinNamefield.
Step3YouwillseeinyoursolutionexplorerthatModelFirstDemoModel.Context.ttand
ModelFirstDemoModel.tttemplatesaregenerated.

http://www.tutorialspoint.com/cgibin/printpage.cgi

54/225

8/12/2016

EntityFrameworkQuickGuide

TheModelFirstDemoModel.ContextgeneratestheDbCcontextandtheobjectsetsthatyoucanreturnanduse
forquerying,sayforcontext,StudentsandCoursesetc.
TheothertemplatedealswithallthetypesStudent,Coursesetc.FollowingistheStudentclass,whichis
generatedautomaticallyfromtheEntityModel.

FollowingistheC#codeinwhichsomedataareenteredandretrievedfromdatabase.
usingSystem;
usingSystem.Linq;
namespaceEFModelFirstDemo{
classProgram{
staticvoidMain(string[]args){
using(vardb=newModelFirstDemoDBContext()){
//CreateandsaveanewStudent
Console.Write("EnteranameforanewStudent:");
varfirstName=Console.ReadLine();
varstudent=newStudent{
StudentID=1,
FirstName=firstName
};

db.Students.Add(student);
db.SaveChanges();

http://www.tutorialspoint.com/cgibin/printpage.cgi

55/225

8/12/2016

EntityFrameworkQuickGuide

varquery=frombindb.Students
orderbyb.FirstNameselectb;
Console.WriteLine("Allstudentinthedatabase:");
foreach(variteminquery){
Console.WriteLine(item.FirstName);
}
Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}
}
}
}

Whentheabovecodeisexecuted,youwillreceivethefollowingoutput
EnteranameforanewStudent:
AliKhan
Allstudentinthedatabase:
AliKhan
Pressanykeytoexit...

Werecommendyoutoexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKDATABASEFIRSTAPPROACH
Inthischapter,letuslearnaboutcreatinganentitydatamodelwithDatabaseFirstapproach.
TheDatabaseFirstApproachprovidesanalternativetotheCodeFirstandModelFirstapproachestothe
EntityDataModel.Itcreatesmodelcodesclasses, properties, DbC ontextetc. fromthedatabaseinthe
projectandthoseclassesbecomethelinkbetweenthedatabaseandcontroller.
TheDatabaseFirstApproachcreatestheentityframeworkfromanexistingdatabase.Weuseallother
functionalities,suchasthemodel/databasesyncandthecodegeneration,inthesamewayweusedthem
intheModelFirstapproach.
Letstakeasimpleexample.Wealreadyhaveadatabasewhichcontains3tablesasshowninthefollowing
image.

http://www.tutorialspoint.com/cgibin/printpage.cgi

56/225

8/12/2016

EntityFrameworkQuickGuide

Step1LetscreateanewconsoleprojectwithDatabaseFirstDemoname.
Step2Tocreatethemodel,firstrightclickonyourconsoleprojectinsolutionexplorerandselectAdd
NewItems

http://www.tutorialspoint.com/cgibin/printpage.cgi

57/225

8/12/2016

EntityFrameworkQuickGuide

Step3SelectADO.NETEntityDataModelfrommiddlepaneandenternameDatabaseFirstModelinthe
Namefield.
Step4ClickAddbuttonwhichwilllaunchtheEntityDataModelWizarddialog.

Step5SelectEFDesignerfromdatabaseandclickNextbutton.

http://www.tutorialspoint.com/cgibin/printpage.cgi

58/225

8/12/2016

EntityFrameworkQuickGuide

Step6SelecttheexistingdatabaseandclickNext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

59/225

8/12/2016

EntityFrameworkQuickGuide

Step7ChooseEntityFramework6.xandclickNext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

60/225

8/12/2016

EntityFrameworkQuickGuide

Step8SelectallthetablesViewsandstoredprocedureyouwanttoincludeandclickFinish.
YouwillseethatEntitymodelandPOCOclassesaregeneratedfromthedatabase.

http://www.tutorialspoint.com/cgibin/printpage.cgi

61/225

8/12/2016

EntityFrameworkQuickGuide

Letusnowretrieveallthestudentsfromthedatabasebywritingthefollowingcodeinprogram.csfile.
usingSystem;
usingSystem.Linq;
namespaceDatabaseFirstDemo{
classProgram{
staticvoidMain(string[]args){
using(vardb=newUniContextEntities()){
varquery=frombindb.Students
orderbyb.FirstMidNameselectb;
Console.WriteLine("AllAllstudentinthedatabase:");
foreach(variteminquery){
Console.WriteLine(item.FirstMidName+""+item.LastName);
}
Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}
}
}
}

Whentheaboveprogramisexecuted,youwillreceivethefollowingoutput
Allstudentinthedatabase:
AliKhan
Arturofinand
BillGates
CarsonAlexander
GytisBarzdukas
LauraNorman
MeredithAlonso
NinoOlivetto
PeggyJustice
YanLi
Pressanykeytoexit...

Whentheaboveprogramisexecuted,youwillseeallthestudentsnamewhichwerepreviouslyenteredinthe
database.
Werecommendyoutoexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKDEVAPPROACHES
Inthischapter,letusfocusonbuildingmodelswiththeDesignerorDatabaseFirstorjustusingCodeFirst.
Followingaresomeguidelineswhichwillhelpyoudecidewhichmodelingworkflowtochoose.
WehavealreadyseenexamplesofCodeFirstmodeling,DatabaseFirstmodelingandaModelFirst
modelingworkflow.
TheDatabaseFirstandModelFirstworkflowsusedtheDesignerbutonestartswiththedatabaseto
createamodelandtheotherstartsatthemodeltocreateadatabase.

http://www.tutorialspoint.com/cgibin/printpage.cgi

62/225

8/12/2016

EntityFrameworkQuickGuide

ForthosedeveloperswhodonotwanttouseVisualDesignerpluscodegeneration,EntityFrameworkhas
acompletelydifferentworkflowcalledCodeFirst.
ThetypicalworkflowforCodeFirstisgreatforbrandnewapplicationswhereyoudon'tevenhavea
database.YoudefineyourclassesandcodeandthenletCodeFirstfigureoutwhatyourdatabaseshould
looklike.
ItisalsopossibletostartCodeFirstwithadatabaseandthatmakesCodeFirstabitofacontradiction.
Butthere'satooltoletyoureverseengineeradatabaseintoclasseswhichisagreatwaytogetahead
startonthecoding.
Giventheseoptions,let'slookattheDecisionTree.
IfyouprefertoworkwithaVisualDesigneringeneratedcode,thenyou'llwanttochooseoneofthe
workflowsthatinvolvesEFDesigner.Ifyourdatabasealreadyexists,thenDatabaseFirstisyourpath.
IfyouwanttouseaVisualDesigneronabrandnewprojectwithoutadatabase,thenyou'llwanttouse
ModelFirst.
IfyoujustwanttoworkwithcodeandnotaDesigner,thenCodeFirstisprobablyforyoualongwiththe
optionofusingthetoolthatreverseengineersthedatabaseintoclasses.
Ifyouhaveexistingclasses,thenyourbestbetistousethemwithCodeFirst.

ENTITYFRAMEWORKDATABASEOPERATIONS
Inthepreviouschapters,youlearnedthreedifferentwaysofdefininganentitydatamodel.
Twoofthem,DatabaseFirstandModelFirst,dependedontheEntityFrameworkdesignercombined
withcodegeneration.

http://www.tutorialspoint.com/cgibin/printpage.cgi

63/225

8/12/2016

EntityFrameworkQuickGuide

Thethird,CodeFirst,letsyouskipavisualdesignerandjustwriteyourowncode.
Regardlessofwhichpathyouchoose,you'llendupwithdomainclassesandoneormoreEntity
FrameworkDbContextclassesallowsyoutoretrieveandpersistdatarelevanttothoseclasses.
TheDbContextAPIinyourapplicationsisusedasabridgebetweenyourclassesandyourdatabase.The
DbContextisoneofthemostimportantclassesintheEntityFramework.
Itenablestoexpressandexecutequeries.
Ittakesqueryresultsfromthedatabaseandtransformsthemintoinstancesofourmodelclasses.
Itcankeeptrackofchangestoentities,includingaddinganddeleting,andthentriggersthecreationof
insert,updateanddeletestatementsthataresenttothedatabaseondemand.
Followingarethedomainadcontextclassesonwhichwewillbeperformingdifferentoperationsinthischapter.
Thisisthesameexamplewhichwehavecreatedinthechapater,DatabaseFirstApproach.

ContextClassImplementation
usingSystem;
usingSystem.Data.Entity;
usingSystem.Data.Entity.Infrastructure;
usingSystem.Data.Entity.Core.Objects;
usingSystem.Linq;
namespaceDatabaseFirstDemo{
publicpartialclassUniContextEntities:DbContext{
publicUniContextEntities():base("name=UniContextEntities"){}
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
thrownewUnintentionalCodeFirstException();
}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}
}

DomainClassesImplementation
Courseclass
namespaceDatabaseFirstDemo{
usingSystem;
usingSystem.Collections.Generic;

publicpartialclassCourse{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2214:DoNotCallOverridableMethodsInConstructors")]
publicCourse(){
this.Enrollments=newHashSet<Enrollment>();
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

64/225

8/12/2016

EntityFrameworkQuickGuide

publicintCourseID{get;set;}
publicstringTitle{get;set;}
publicintCredits{get;set;}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2227:CollectionPropertiesShouldBeReadOnly")]

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
}

Studentclass
namespaceDatabaseFirstDemo{
usingSystem;
usingSystem.Collections.Generic;
publicpartialclassStudent{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2214:DoNotCallOverridableMethodsInConstructors")]
publicStudent(){
this.Enrollments=newHashSet<Enrollment>();
}
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicSystem.DateTimeEnrollmentDate{get;set;}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2227:CollectionPropertiesShouldBeReadOnly")]

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
}

Enrollmentclass
namespaceDatabaseFirstDemo{
usingSystem;
usingSystem.Collections.Generic;
publicpartialclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicNullable<int>Grade{get;set;}

publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}
}

CreateOperation

http://www.tutorialspoint.com/cgibin/printpage.cgi

65/225

8/12/2016

EntityFrameworkQuickGuide

AddinganewobjectwithEntityFrameworkisassimpleasconstructinganewinstanceofyourobjectand
registeringitusingtheAddmethodonDbSet.Thefollowingcodeletsyouaddanewstudenttothedatabase.
classProgram{
staticvoidMain(string[]args){
varnewStudent=newStudent();
//setstudentname
newStudent.FirstMidName="Bill";
newStudent.LastName="Gates";
newStudent.EnrollmentDate=DateTime.Parse("20151021");
newStudent.ID=100;
//createDBContextobject
using(vardbCtx=newUniContextEntities()){
//AddStudentobjectintoStudentsDBset
dbCtx.Students.Add(newStudent);
//callSaveChangesmethodtosavestudentintodatabase
dbCtx.SaveChanges();
}
}
}

UpdateOperation
Changingexistingobjectsisassimpleasupdatingthevalueassignedtothepropertysyouwantchangedand
callingSaveChanges.Forexample,thefollowingcodeisusedtochangethelastnameofAlifromKhantoAslam.
using(varcontext=newUniContextEntities()){
varstudent=(fromdincontext.Studentswhered.FirstMidName=="Ali"selectd).Single();
student.LastName="Aslam";
context.SaveChanges();
}

DeleteOperation
TodeleteanentityusingEntityFramework,youusetheRemovemethodonDbSet.Removeworksforboth
existingandnewlyaddedentities.CallingRemoveonanentitythathasbeenaddedbutnotyetsavedtothe
databasewillcanceltheadditionoftheentity.Theentityisremovedfromthechangetrackerandisnolonger
trackedbytheDbContext.CallingRemoveonanexistingentitythatisbeingchangetrackedwillregisterthe
entityfordeletionthenexttimeSaveChangesiscalled.Thefollowingexampleisofacodewherethestudentis
removedfromthedatabasewhosefirstnameisAli.
using(varcontext=newUniContextEntities()){
varbay=(fromdincontext.Studentswhered.FirstMidName=="Ali"selectd).Single();
context.Students.Remove(bay);
context.SaveChanges();
}

ReadOperation

http://www.tutorialspoint.com/cgibin/printpage.cgi

66/225

8/12/2016

EntityFrameworkQuickGuide

Readingtheexistingdatafromthedatabaseisverysimple.Followingisthecodeinwhichallthedatafromthe
Studenttableareretrievedandthenaprogramwillbedisplayedwiththestudentsfirstandlastnamein
alphabeticalorder.
using(vardb=newUniContextEntities()){
varquery=frombindb.Studentsorderbyb.FirstMidNameselectb;
Console.WriteLine("AllAllstudentinthedatabase:");
foreach(variteminquery){
Console.WriteLine(item.FirstMidName+""+item.LastName);
}
Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}

ENTITYFRAMEWORKCONCURRENCY
Anydataaccessdeveloperfacesdifficultywhileansweringthequestionregardingdataconcurrency,What
happensifmorethanonepersoniseditingthesamedataatthesametime?
Themorefortunateamongusdealwithbusinessrulesthatsaynoproblem,lastoneinwins.
Inthiscase,concurrencyisnotanissue.Morelikely,itsnotassimpleasthat,andthereisnosilverbullet
tosolveeveryscenarioatonce.
Bydefault,theEntityFrameworkwilltakethepathoflastoneinwins,meaningthatthelatestupdateis
appliedevenifsomeoneelseupdatedthedatabetweenthetimedatawasretrievedandthetimedatawas
saved.
Letstakeanexampletounderstanditbetter.ThefollowingexampleaddsanewcolumnVersionNoinCourse
table.

http://www.tutorialspoint.com/cgibin/printpage.cgi

67/225

8/12/2016

EntityFrameworkQuickGuide

Gotothedesignerandrightclickonthedesignerwindowandselectupdatemodelfromdatabase

http://www.tutorialspoint.com/cgibin/printpage.cgi

68/225

8/12/2016

EntityFrameworkQuickGuide

YouwillseethatanothercolumnisaddedinCourseEntity.

http://www.tutorialspoint.com/cgibin/printpage.cgi

69/225

8/12/2016

EntityFrameworkQuickGuide

RightclickonthenewlycreatedcolumnVersionNoandselectPropertiesandchangetheConcurrencyModeto
Fixedasshowninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

70/225

8/12/2016

EntityFrameworkQuickGuide

WiththeConcurrencyModeofCourse.VersionNosettoFixed,anytimeaCourseisupdated,theUpdate
commandwilllookfortheCourseusingitsEntityKeyanditsVersionNoproperty.
Letstakealookatasimplescenario.Twousersretrievethesamecourseatthesametimeanduser1changes
thetitleofthatcoursetoMathsandsaveschangesbeforeuser2.Laterwhenuser2changesthetitleofthat
coursewhichwasretrievedbeforeuser1savehischanges,inthatcaseuser2willgetconcurrencyexception
"User2:OptimisticConcurrencyexceptionoccured".
usingSystem;
usingSystem.Data.Entity;
usingSystem.Data.Entity.Infrastructure;
usingSystem.Linq;
namespaceDatabaseFirstDemo{
classProgram{
staticvoidMain(string[]args){
Coursec1=null;
Coursec2=null;
//User1getsCourse
using(varcontext=newUniContextEntities()){
context.Configuration.ProxyCreationEnabled=false;
c1=context.Courses.Where(ss.CourseID==1).Single();
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

71/225

8/12/2016

EntityFrameworkQuickGuide

//User2alsogetthesameCourse
using(varcontext=newUniContextEntities()){
context.Configuration.ProxyCreationEnabled=false;
c2=context.Courses.Where(ss.CourseID==1).Single();
}
//User1updatesCourseTitle
c1.Title="Editedfromuser1";
//User2updatesCourseTitle
c2.Title="Editedfromuser2";
//User1saveschangesfirst
using(varcontext=newUniContextEntities()){
try{
context.Entry(c1).State=EntityState.Modified;
context.SaveChanges();
}catch(DbUpdateConcurrencyExceptionex){
Console.WriteLine("User1:OptimisticConcurrencyexceptionoccurred");
}
}
//User2saveschangesafterUser1.
//User2willgetconcurrencyexection
//becauseCreateOrModifiedDateisdifferentinthedatabase
using(varcontext=newUniContextEntities()){
try{
context.Entry(c2).State=EntityState.Modified;
context.SaveChanges();
}catch(DbUpdateConcurrencyExceptionex){
Console.WriteLine("User2:OptimisticConcurrencyexceptionoccurred");
}
}
}
}
}

ENTITYFRAMEWORKTRANSACTION
InallversionsofEntityFramework,wheneveryouexecuteSaveChangestoinsert,updateordeletethe
database,theframeworkwillwrapthatoperationinatransaction.WhenyouinvokeSaveChanges,thecontext
automaticallystartsatransactionandcommitsorrollsitbackdependingonwhetherthepersistencesucceeded.
Thisisalltransparenttoyou,andyoullneverneedtodealwithit.
Thistransactionlastsonlylongenoughtoexecutetheoperationandthencompletes.
Whenyouexecuteanothersuchoperation,anewtransactionstarts.
EntityFramework6providesthefollowing

Database.BeginTransaction

http://www.tutorialspoint.com/cgibin/printpage.cgi

72/225

8/12/2016

EntityFrameworkQuickGuide

ItisasimpleandeasiermethodwithinanexistingDbContexttostartandcompletetransactionsfor
users.
Itallowsseveraloperationstobecombinedwithinthesametransactionandhenceeitherallare
committedorallarerolledbackasone.
Italsoallowstheusertomoreeasilyspecifytheisolationlevelforthetransaction.

Database.UseTransaction
ItallowstheDbContexttouseatransaction,whichwasstartedoutsideoftheEntityFramework.
Letstakealookintothefollowingexamplewheremultipleoperationsareperformedinasingletransaction.
Thecodeisas
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
using(vardbContextTransaction=context.Database.BeginTransaction()){
try{
Studentstudent=newStudent(){
ID=200,
FirstMidName="Ali",
LastName="Khan",
EnrollmentDate=DateTime.Parse("2015121")
};
context.Students.Add(student);
context.Database.ExecuteSqlCommand(@"UPDATECourseSETTitle=
'Calculus'"+"WHERECourseID=1045");
varquery=context.Courses.Where(cc.CourseID==1045);
foreach(variteminquery){
Console.WriteLine(item.CourseID.ToString()
+""+item.Title+""+item.Credits);
}
context.SaveChanges();
varquery1=context.Students.Where(ss.ID==200);
foreach(variteminquery1){
Console.WriteLine(item.ID.ToString()
+""+item.FirstMidName+""+item.LastName);
}
dbContextTransaction.Commit();
}catch(Exception){
dbContextTransaction.Rollback();
}
}
}
}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

73/225

8/12/2016

EntityFrameworkQuickGuide

Beginningatransactionrequiresthattheunderlyingstoreconnectionisopen.
SocallingDatabase.BeginTransactionwillopentheconnection,ifitisnotalreadyopened.
IfDbContextTransactionopenedtheconnectionthenitwillcloseitwhenDisposeiscalled.

ENTITYFRAMEWORKVIEWS
Aviewisanobjectthatcontainsdataobtainedbyapredefinedquery.Aviewisavirtualobjectortablewhose
resultsetisderivedfromaquery.Itisverysimilartoarealtablebecauseitcontainscolumnsandrowsofdata.
Followingaresometypicalusesofviews
Filterdataofunderlyingtables
Filterdataforsecuritypurposes
Centralizedatadistributedacrossseveralservers
Createareusablesetofdata
Viewscanbeusedinasimilarwayasyoucanusetables.Touseviewasanentity,firstyouwillneedtoadd
databaseviewstoEDM.Afteraddingviewstoyourmodelthenyoucanworkwithitthesamewayasnormal
entitiesexceptforCreate,Update,andDeleteoperations.
Letstakealook,howtoaddviewsintothemodelfromthedatabase.
Step1CreateanewConsoleApplicationproject.

Step2RightclickonprojectinsolutionexplorerandselectAddNewItem.

http://www.tutorialspoint.com/cgibin/printpage.cgi

74/225

8/12/2016

EntityFrameworkQuickGuide

Step3SelectADO.NETEntityDataModelfromthemiddlepaneandenternameViewModelintheName
field.
Step4ClickAddbuttonwhichwilllaunchtheEntityDataModelWizarddialog.

http://www.tutorialspoint.com/cgibin/printpage.cgi

75/225

8/12/2016

EntityFrameworkQuickGuide

Step5SelectEFDesignerfromdatabaseandclickNextbutton.

http://www.tutorialspoint.com/cgibin/printpage.cgi

76/225

8/12/2016

EntityFrameworkQuickGuide

Step6SelecttheexistingdatabaseandclickNext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

77/225

8/12/2016

EntityFrameworkQuickGuide

Step7ChooseEntityFramework6.xandclickNext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

78/225

8/12/2016

EntityFrameworkQuickGuide

Step8SelecttablesandviewsfromyourdatabaseandclickFinish.

http://www.tutorialspoint.com/cgibin/printpage.cgi

79/225

8/12/2016

EntityFrameworkQuickGuide

Youcanseeinthedesignerwindowthataviewiscreatedandyoucanuseitintheprogramasanentity.
Inthesolutionexplorer,youcanseethatMyViewclassisalsogeneratedfromthedatabase.
Letstakeanexampleinwhichalldataisretrievedfromview.Followingisthecode
classProgram{
staticvoidMain(string[]args){
using(vardb=newUniContextEntities()){
varquery=frombindb.MyViews
orderbyb.FirstMidNameselectb;
Console.WriteLine("Allstudentinthedatabase:");
foreach(variteminquery){
Console.WriteLine(item.FirstMidName+""+item.LastName);
}
Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}
}
}

Whentheabovecodeisexecuted,youwillreceivethefollowingoutput

http://www.tutorialspoint.com/cgibin/printpage.cgi

80/225

8/12/2016

EntityFrameworkQuickGuide

Allstudentinthedatabase:
AliKhan
Arturofinand
BillGates
CarsonAlexander
GytisBarzdukas
LauraNorman
MeredithAlonso
NinoOlivetto
PeggyJustice
YanLi
Pressanykeytoexit...

Werecommendyoutoexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKINDEX
Anindexisanondiskdatastructurethatisbasedontablesandviews.Indexesmaketheretrievalofdatafaster
andefficient,inmostcases.However,overloadingatableorviewwithindexescouldunpleasantlyaffectthe
performanceofotheroperationssuchasinsertsorupdates.
IndexingisthenewfeatureinentityframeworkwhereyoucanimprovetheperformanceofyourCode
Firstapplicationbyreducingthetimerequiredtoquerydatafromthedatabase.
YoucanaddindexestoyourdatabaseusingtheIndexattribute,andoverridethedefaultUniqueand
Clusteredsettingstogettheindexbestsuitedtoyourscenario.
LetstakealookatthefollowingcodeinwhichIndexattributeisaddedinCourseclassforCourseID.
publicpartialclassCourse{
publicCourse(){
this.Enrollments=newHashSet<Enrollment>();
}
[Index]
publicintCourseID{get;set;}
publicstringTitle{get;set;}

publicintCredits{get;set;}
publicbyte[]VersionNo{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Thekeycreatedaboveisnonunique,nonclustered.Thereareoverloadsavailabletooverridethesedefaults
TomakeanindexaClusteredindex,youneedtospecifyIsClustered=true
Similarly,youcanalsomakeanindexauniqueindexbyspecifyingIsUnique=true
LetstakealookatthefollowingC#codewhereanindexisclusteredandunique.
publicpartialclassCourse{
publicCourse(){
this.Enrollments=newHashSet<Enrollment>();
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

81/225

8/12/2016

EntityFrameworkQuickGuide

[Index(IsClustered=true,IsUnique=true)]
publicintCourseID{get;set;}
publicstringTitle{get;set;}

publicintCredits{get;set;}
publicbyte[]VersionNo{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Indexattributecanbeusedtocreateauniqueindexinthedatabase.However,thisdoesnotmeanthatEFwill
beabletoreasonabouttheuniquenessofthecolumnwhendealingwithrelationships,etc.Thisfeatureis
usuallyreferredtoassupportforuniqueconstraints.

ENTITYFRAMEWORKSTOREDPROCEDURES
TheEntityFrameworkallowsyoutousestoredproceduresintheEntityDataModelinsteadof,orin
combinationwith,itsautomaticcommandgeneration.
Youcanusestoredprocedurestoperformpredefinedlogicondatabasetables,andmanyorganizations
havepoliciesinplacethatrequiretheuseofthesestoredprocedures.
ItcanalsospecifythatEFshoulduseyourstoredproceduresforinserting,updating,ordeletingentities.
Althoughthedynamicallybuiltcommandsaresecure,efficient,andgenerallyasgoodasorbetterthan
thoseyoumaywriteyourself,therearemanycaseswherestoredproceduresalreadyexistandyour
companypracticesmayrestrictdirectuseofthetables.
Alternatively,youmayjustwanttohaveexplicitcontroloverwhatisexecutedonthestoreandpreferto
createstoredprocedures.
ThefollowingexamplecreatesanewprojectfromFileNewProject.

http://www.tutorialspoint.com/cgibin/printpage.cgi

82/225

8/12/2016

EntityFrameworkQuickGuide

Step1SelecttheConsoleApplicationfromthemiddlepaneandenterStoredProceduresDemointhename
field.
Step2InServerexplorerrightclickonyourdatabase.
Step3SelectNewQueryandenterthefollowingcodeinTSQLeditortoaddanewtableinyourdatabase.
IFNOTEXISTS(SELECT*FROMsys.objectsWHEREobject_id=
OBJECT_ID(N'[dbo].[StudentGrade]')ANDtypein(N'U'))
BEGIN
CREATETABLE[dbo].[StudentGrade](
[EnrollmentID][int]IDENTITY(1,1)NOTNULL,
[CourseID][int]NOTNULL,
[StudentID][int]NOTNULL,
[Grade][decimal](3,2)NULL,
CONSTRAINT[PK_StudentGrade]PRIMARYKEYCLUSTERED(
[EnrollmentID]ASC
)
WITH(IGNORE_DUP_KEY=OFF)ON[PRIMARY]
)ON[PRIMARY]
END
GO

http://www.tutorialspoint.com/cgibin/printpage.cgi

83/225

8/12/2016

EntityFrameworkQuickGuide

Step4RightclickontheeditorandselectExecute.

Step5Rightclickonyourdatabaseandclickrefresh.Youwillseethenewlyaddedtableinyourdatabase.
Step6InServerexplorer,rightclickonyourdatabaseagain.

http://www.tutorialspoint.com/cgibin/printpage.cgi

84/225

8/12/2016

EntityFrameworkQuickGuide

Step7SelectNewQueryandenterthefollowingcodeinTSQLeditortoaddastoredprocedureinyour
database,whichwillreturntheStudentgrades.
IFNOTEXISTS(SELECT*FROMsys.objectsWHEREobject_id=
OBJECT_ID(N'[dbo].[GetStudentGrades]')ANDtypein(N'P',N'PC'))
BEGIN
EXECdbo.sp_executesql@statement=N'
CREATEPROCEDURE[dbo].[GetStudentGrades]
@StudentIDint
AS
SELECTEnrollmentID,Grade,CourseID,StudentIDFROMdbo.StudentGrade
WHEREStudentID=@StudentID
'
END
GO

Step8RightclickontheeditorandselectExecute.

http://www.tutorialspoint.com/cgibin/printpage.cgi

85/225

8/12/2016

EntityFrameworkQuickGuide

Step9Rightclickonyourdatabaseandclickrefresh.Youwillseethatastoredprocedureiscreatedinyour
database.

http://www.tutorialspoint.com/cgibin/printpage.cgi

86/225

8/12/2016

EntityFrameworkQuickGuide

Step10RightclickontheprojectnameinSolutionExplorerandselectAddNewItem.
Step11ThenselectADO.NETEntityDataModelintheTemplatespane.

Step12EnterSPModelasname,andthenclickAdd.
Step13IntheChooseModelContentsdialogbox,selectEFdesignerfromdatabase,andthenclickNext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

87/225

8/12/2016

EntityFrameworkQuickGuide

Step14SelectyourdatabaseandclickNext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

88/225

8/12/2016

EntityFrameworkQuickGuide

Step15IntheChooseYourDatabaseObjectsdialogboxclickontables,views.

http://www.tutorialspoint.com/cgibin/printpage.cgi

89/225

8/12/2016

EntityFrameworkQuickGuide

Step16SelecttheGetStudentGradesForCoursefunctionlocatedundertheStoredProceduresandFunctions
nodeandclickFinish.
Step17SelectViewOtherWindowsEntityDataModelBrowserandrightclickGetStudentGrades
underFunctionImportsandselectEdit.

http://www.tutorialspoint.com/cgibin/printpage.cgi

90/225

8/12/2016

EntityFrameworkQuickGuide

Itwillproducethefollowingdialog.

http://www.tutorialspoint.com/cgibin/printpage.cgi

91/225

8/12/2016

EntityFrameworkQuickGuide

Step18ClickonEntitiesradiobuttonandselectStudentGradefromthecomboboxasreturntypeofthis
storedprocedureandclickOk.
LetstakealookatthefollowingC#codeinwhichallthegradeswillberetrievedbypassingthestudentIDas
parameterinGetStudentGradesstoredprocedure.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
intstudentID=22;
varstudentGrades=context.GetStudentGrades(studentID);
foreach(varstudentinstudentGrades){
Console.WriteLine("CourseID:{0},Title:{1},Grade:{2}",
student.CourseID,student.Course.Title,student.Grade);
}
Console.ReadKey();
}
}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

92/225

8/12/2016

EntityFrameworkQuickGuide

Whentheabovecodeiscompiledandexecutedyouwillreceivethefollowingoutput
CourseID:4022,Title:Microeconomics,Grade:3.00
CourseID:4041,Title:Macroeconomics,Grade:3.50

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKDISCONNECTEDENTITIES
Inthischapter,letuslookathowtomakechangestoentitiesthatarenotbeingtrackedbyacontext.Entities
thatarenotbeingtrackedbyacontextareknownasdisconnectedentities.
Formostsingletierapplications,wheretheuserinterfaceanddatabaseaccesslayersruninthesame
applicationprocess,youwillprobablyjustbeperformingoperationsonentitiesthatarebeingtrackedby
acontext.
OperationsondisconnectedentitiesaremuchmorecommoninNTierapplications.
NTierapplicationsinvolvefetchingsomedataonaserverandreturningit,overthenetwork,toaclient
machine.
Theclientapplicationthenmanipulatesthisdatabeforereturningittotheservertobepersisted.
Followingarethetwostepsthatneedstobetakenwithdisconnectedentitygraphorevenasingledisconnected
entity.
Attachentitieswiththenewcontextinstanceandmakecontextawareabouttheseentities.
SetappropriateEntityStatestotheseentitiesmanually.

LetstakealookatthefollowingcodeinwhichStudententityisaddedwithtwoEnrollmententities.

http://www.tutorialspoint.com/cgibin/printpage.cgi

93/225

8/12/2016

EntityFrameworkQuickGuide

classProgram{
staticvoidMain(string[]args){
varstudent=newStudent{
ID=1001,
FirstMidName="Wasim",
LastName="Akram",
EnrollmentDate=DateTime.Parse("20151010"),
Enrollments=newList<Enrollment>{
newEnrollment{EnrollmentID=2001,CourseID=4022,StudentID=1001},
newEnrollment{EnrollmentID=2002,CourseID=4025,StudentID=1001},
}
};
using(varcontext=newUniContextEntities()){
context.Students.Add(student);
Console.WriteLine("NewStudent({0}{1}):{2}",
student.FirstMidName,student.LastName,context.Entry(student).State);
foreach(varenrollmentinstudent.Enrollments){
Console.WriteLine("EnrollmentID:{0}State:{1}",
enrollment.EnrollmentID,context.Entry(enrollment).State);
}
Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}
}
}

ThecodeconstructsanewStudentinstance,whichalsoreferencestwonewEnrollmentinstancesinits
Enrollmentsproperty.
ThenthenewStudentisaddedtoacontextusingtheAddmethod.
OncetheStudentisadded,thecodeusestheDbContext.Entrymethodtogetaccesstothechangetracking
informationthatEntityFrameworkhasaboutthenewStudent.
Fromthischangetrackinginformation,theStatepropertyisusedtowriteoutthecurrentstateofthe
entity.
ThisprocessisthenrepeatedforeachofthenewlycreatedEnrollmentsthatarereferencedfromthenew
Student.Ifyouruntheapplication,youwillreceivethefollowingoutput
NewStudent(WasimAkram):Added
EnrollmentID:2001State:Added
EnrollmentID:2002State:Added
Pressanykeytoexit...

WhileDbSet.AddisusedtotellEntityFrameworkaboutnewentities,DbSet.AttachisusedtotellEntity
Frameworkaboutexistingentities.TheAttachmethodwillmarkanentityintheUnchangedstate.
LetstakealookatthefollowingC#codeinwhichadisconnectedentityisattachedwithDbContext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

94/225

8/12/2016

EntityFrameworkQuickGuide

classProgram{
staticvoidMain(string[]args){
varstudent=newStudent{
ID=1001,
FirstMidName="Wasim",
LastName="Akram",
EnrollmentDate=DateTime.Parse("20151010"),
Enrollments=newList<Enrollment>{
newEnrollment{EnrollmentID=2001,CourseID=4022,StudentID=1001},
newEnrollment{EnrollmentID=2002,CourseID=4025,StudentID=1001},
}

};
using(varcontext=newUniContextEntities()){
context.Students.Attach(student);
Console.WriteLine("NewStudent({0}{1}):{2}",
student.FirstMidName,student.LastName,context.Entry(student).State);
foreach(varenrollmentinstudent.Enrollments){
Console.WriteLine("EnrollmentID:{0}State:{1}",enrollment.EnrollmentID,
context.Entry(enrollment).State);
}
Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}
}
}

WhentheabovecodeisexecutedwithAttachmethod,youwillreceivethefollowingoutput.
NewStudent(WasimAkram):Unchanged
EnrollmentID:2001State:Unchanged
EnrollmentID:2002State:Unchanged
Pressanykeytoexit...

ENTITYFRAMEWORKTABLEVALUEDFUNCTION
Inthischapter,letuslearnhowtomapTablevaluedFunctionsT V F s usingtheEntityFrameworkDesignerand
howtocallaTVFfromaLINQquery.
TVFsarecurrentlyonlysupportedintheDatabaseFirstworkflow.
ItwasfirstintroducedinEntityFrameworkversion5.
TousetheTVFsyoumusttarget.NETFramework4.5orabove.
Itisverysimilartostoredproceduresbutwithonekeydifference,i.e.,theresultofaTVFiscomposable.
ThismeanstheresultsfromaTVFcanbeusedinaLINQquerywhiletheresultsofastoredprocedure
cannot.
LetstakealookatthefollowingexampleofcreatinganewprojectfromFileNewProject.

http://www.tutorialspoint.com/cgibin/printpage.cgi

95/225

8/12/2016

EntityFrameworkQuickGuide

Step1SelecttheConsoleApplicationfromthemiddlepaneandenterTableValuedFunctionDemointhe
namefield.
Step2InServerexplorerrightclickonyourdatabase.

http://www.tutorialspoint.com/cgibin/printpage.cgi

96/225

8/12/2016

EntityFrameworkQuickGuide

Step3SelectNewQueryandenterthefollowingcodeinTSQLeditortoaddanewtableinyourdatabase.
IFNOTEXISTS(SELECT*FROMsys.objectsWHEREobject_id=
OBJECT_ID(N'[dbo].[StudentGrade]')ANDtypein(N'U'))
BEGIN
CREATETABLE[dbo].[StudentGrade](
[EnrollmentID][int]IDENTITY(1,1)NOTNULL,
[CourseID][int]NOTNULL,
[StudentID][int]NOTNULL,
[Grade][decimal](3,2)NULL,
CONSTRAINT[PK_StudentGrade]PRIMARYKEYCLUSTERED([EnrollmentID]ASC)
WITH(IGNORE_DUP_KEY=OFF)ON[PRIMARY]
)ON[PRIMARY]
END
GO

Step4RightclickontheeditorandselectExecute.

http://www.tutorialspoint.com/cgibin/printpage.cgi

97/225

8/12/2016

EntityFrameworkQuickGuide

Step5Rightclickonyourdatabaseandclickrefresh.Youwillseethenewlyaddedtableinyourdatabase.

http://www.tutorialspoint.com/cgibin/printpage.cgi

98/225

8/12/2016

EntityFrameworkQuickGuide

Step6Nowcreateafunctionthatwillreturnstudentgradesforcourse.EnterthefollowingcodeinTSQL
editor.
CREATEFUNCTION[dbo].[GetStudentGradesForCourse]
(@CourseIDINT)
RETURNSTABLE
RETURN
SELECT[EnrollmentID],
[CourseID],
[StudentID],
[Grade]
FROM[dbo].[StudentGrade]
WHERECourseID=@CourseID

Step7RightclickontheeditorandselectExecute.

Nowyoucanseethatthefunctioniscreated.

http://www.tutorialspoint.com/cgibin/printpage.cgi

99/225

8/12/2016

EntityFrameworkQuickGuide

Step8RightclickontheprojectnameinSolutionExplorerandselectAddNewItem.
Step9ThenselectADO.NETEntityDataModelintheTemplatespane.

http://www.tutorialspoint.com/cgibin/printpage.cgi

100/225

8/12/2016

EntityFrameworkQuickGuide

Step10EnterTVFModelasname,andthenclickAdd.
Step11IntheChooseModelContentsdialogbox,selectEFdesignerfromdatabase,andthenclickNext.

Step12SelectyourdatabaseandclickNext.

http://www.tutorialspoint.com/cgibin/printpage.cgi

101/225

8/12/2016

EntityFrameworkQuickGuide

Step13IntheChooseYourDatabaseObjectsdialogboxselecttables,views.

http://www.tutorialspoint.com/cgibin/printpage.cgi

102/225

8/12/2016

EntityFrameworkQuickGuide

Step14SelecttheGetStudentGradesForCoursefunctionlocatedundertheStoredProceduresandFunctions
nodeandclickFinish.
Step15SelectViewOtherWindowsEntityDataModelBrowserandrightclick
GetStudentGradesForCourseunderFunctionImportsandselectEdit.

http://www.tutorialspoint.com/cgibin/printpage.cgi

103/225

8/12/2016

EntityFrameworkQuickGuide

Youwillseethefollowingdialog.

http://www.tutorialspoint.com/cgibin/printpage.cgi

104/225

8/12/2016

EntityFrameworkQuickGuide

Step16ClickonEntitiesradiobuttonandselectEnrollmentfromthecomboboxasreturntypeofthis
FunctionandclickOk.
LetstakealookatthefollowingC#codeinwhichallthestudentsgradewillberetrievedwhoareenrolledin
CourseID=4022indatabase.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
varCourseID=4022;
//ReturnallthebeststudentsintheMicroeconomicsclass.
varstudents=context.GetStudentGradesForCourse(CourseID);
foreach(varresultinstudents){
Console.WriteLine("StudentID:{0},Grade:{1}",
result.StudentID,result.Grade);
}
Console.ReadKey();
}
}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

105/225

8/12/2016

EntityFrameworkQuickGuide

Whentheabovecodeiscompiledandexecutedyouwillreceivethefollowingoutput
StudentID:1,Grade:2
StudentID:4,Grade:4
StudentID:9,Grade:3.5

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKNATIVESQL
InEntityFrameworkyoucanquerywithyourentityclassesusingLINQ.YoucanalsorunqueriesusingrawSQL
directlyagainstthedatabaseusingDbCOntext.Thetechniquescanbeappliedequallytomodelscreatedwith
CodeFirstandEFDesigner.

SQLQueryonExistingEntity
TheSqlQuerymethodonDbSetallowsarawSQLquerytobewrittenthatwillreturnentityinstances.The
returnedobjectswillbetrackedbythecontextjustastheywouldbeiftheywerereturnedbyaLINQquery.For
example
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
varstudents=context.Students.SqlQuery("SELECT*FROMdbo.Student").ToList();
foreach(varstudentinstudents){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1},\tEnrollmentDate{2}",
student.ID,name,student.EnrollmentDate.ToString());
}
Console.ReadKey();
}
}
}

Theabovecodewillretrieveallthestudentsfromthedatabase.

SQLQueryforNonentityTypes
ASQLqueryreturninginstancesofanytype,includingprimitivetypes,canbecreatedusingtheSqlQuery
methodontheDatabaseclass.Forexample
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
varstudentNames=context.Database.SqlQuery
<string>("SELECTFirstMidNameFROMdbo.Student").ToList();
foreach(varstudentinstudentNames){
Console.WriteLine("Name:{0}",student);

http://www.tutorialspoint.com/cgibin/printpage.cgi

106/225

8/12/2016

EntityFrameworkQuickGuide

}
Console.ReadKey();
}
}
}

SQLCommandstotheDatabase
ExecuteSqlCommnadmethodisusedinsendingnonquerycommandstothedatabase,suchastheInsert,
UpdateorDeletecommand.LetstakealookatthefollowingcodeinwhichstudentsfirstnameisupdatedasID
=1
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
//Updatecommand
intnoOfRowUpdated=context.Database.ExecuteSqlCommand("Update
studentsetFirstMidName='Ali'whereID=1");
context.SaveChanges();
varstudent=context.Students.SqlQuery("SELECT*FROM
dbo.StudentwhereID=1").Single();
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1},\tEnrollmentDate{2}",
student.ID,name,student.EnrollmentDate.ToString());
Console.ReadKey();
}
}
}

Theabovecodewillretrieveallthestudentsfirstnamefromthedatabase.

ENTITYFRAMEWORKENUMSUPPORT
InEntityFramework,thisfeaturewillallowyoutodefineapropertyonadomainclassthatisanenumtypeand
mapittoadatabasecolumnofanintegertype.EntityFrameworkwillthenconvertthedatabasevaluetoand
fromtherelevantenumasitqueriesandsavesdata.
Enumeratedtypeshaveallsortsofbenefitswhenworkingwithpropertiesthathaveafixednumberof
responses.
Thesecurityandreliabilityofanapplicationbothincreasewhenyouuseenumerations.
Enumerationmakesitmuchharderfortheusertomakemistakes,andissuessuchasinjectionattacksare
nonexistent.
InEntityFramework,anenumerationcanhavethefollowingunderlyingtypes
Byte
Int16

http://www.tutorialspoint.com/cgibin/printpage.cgi

107/225

8/12/2016

EntityFrameworkQuickGuide

Int32
Int64
SByte
Thedefaultunderlyingtypeoftheenumerationelementsisint.
Bydefault,thefirstenumeratorhasthevalue0,andthevalueofeachsuccessiveenumeratorisincreased
by1.
Letstakealookatthefollowingexampleinwhichwewillbecreatinganentityindesignerandthenwilladd
someproperties.
Step1CreatenewprojectfromFileNewProjectmenuoption.
Step2Intheleftpane,selecttheConsoleApplication.

Step3EnterEFEnumDemoasthenameoftheprojectandclickOK.
Step4RightclickontheprojectnameinSolutionExplorerandselectAddNewItemmenuoption.
Step5SelectADO.NETEntityDataModelintheTemplatespane.

http://www.tutorialspoint.com/cgibin/printpage.cgi

108/225

8/12/2016

EntityFrameworkQuickGuide

Step6EnterEFEnumModel.edmxforthefilename,andthenclickAdd.
Step7OntheEntityDataModelWizardpage,selectEmptyEFdesignerModel.

http://www.tutorialspoint.com/cgibin/printpage.cgi

109/225

8/12/2016

EntityFrameworkQuickGuide

Step8ClickFinish
Step9ThenrightclickondesignerwindowandselectAddEntity.

http://www.tutorialspoint.com/cgibin/printpage.cgi

110/225

8/12/2016

EntityFrameworkQuickGuide

TheNewEntitydialogboxappearsasshowninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

111/225

8/12/2016

EntityFrameworkQuickGuide

Step10EnterDepartmentasanEntitynameandDeptIDasapropertyname,leavethePropertytypeas
Int32andclickOK.
Step11RightclicktheentityandselectAddNewScalarProperty.

http://www.tutorialspoint.com/cgibin/printpage.cgi

112/225

8/12/2016

EntityFrameworkQuickGuide

Step12RenamethenewpropertytoDeptName.
Step13ChangethetypeofthenewpropertytoInt32bydef ault, thenewpropertyisof S tringtype .
Step14Tochangethetype,openthePropertieswindowandchangetheTypepropertytoInt32.

http://www.tutorialspoint.com/cgibin/printpage.cgi

113/225

8/12/2016

EntityFrameworkQuickGuide

Step15IntheEntityFrameworkDesigner,rightclicktheNameproperty,selectConverttoenum.

http://www.tutorialspoint.com/cgibin/printpage.cgi

114/225

8/12/2016

EntityFrameworkQuickGuide

Step16IntheAddEnumTypedialogbox,enterDepartmentNamesfortheEnumTypeName,changethe
UnderlyingTypetoInt32,andthenaddthefollowingmemberstothetype:Physics,Chemistry,Computer,and
Economics.

http://www.tutorialspoint.com/cgibin/printpage.cgi

115/225

8/12/2016

EntityFrameworkQuickGuide

Step17ClickOk.
IfyouswitchtotheModelBrowserwindow,youwillseethatthetypewasalsoaddedtotheEnumTypesnode.

http://www.tutorialspoint.com/cgibin/printpage.cgi

116/225

8/12/2016

EntityFrameworkQuickGuide

LetsgeneratedatabasefrommodelbyfollowingallthestepsmentionedinModelFirstapproachchapter.
Step1RightclickEntityDesignersurfaceandselectGenerateDatabasefromModel.
TheChooseYourDataConnectionDialogBoxoftheGenerateDatabaseWizardisdisplayed.
Step2ClicktheNewConnectionbutton.

http://www.tutorialspoint.com/cgibin/printpage.cgi

117/225

8/12/2016

EntityFrameworkQuickGuide

Step3EntertheservernameandEnumDemoforthedatabaseandclickOK.
Step4Adialogaskingifyouwanttocreateanewdatabasewillpopup,clickYes.
Step5ClickNextandtheCreateDatabaseWizardgeneratesdatadefinitionlanguageDDLforcreatinga
database.NowclickFinish.
Step6RightclickonTSQLEditorandselectExecute.

http://www.tutorialspoint.com/cgibin/printpage.cgi

118/225

8/12/2016

EntityFrameworkQuickGuide

Step7Toviewthegeneratedschema,rightclickonthedatabasenameinSQLServerObjectExplorerand
selectRefresh.
YouwillseetheDepartmentstableinthedatabase.

http://www.tutorialspoint.com/cgibin/printpage.cgi

119/225

8/12/2016

EntityFrameworkQuickGuide

LetstakealookatthefollowingexampleinwhichsomenewDepartmentobjectstothecontextareaddedand
saved.AndthenretrievetheComputerdepartment.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newEFEnumModelContainer()){
context.Departments.Add(newDepartment{DeptName=DepartmentNames.Physics});
context.Departments.Add(newDepartment{DeptName=DepartmentNames.Computer});
context.Departments.Add(newDepartment{DeptName=DepartmentNames.Chemistry});
context.Departments.Add(newDepartment{DeptName=DepartmentNames.Economics});
context.SaveChanges();
vardepartment=(
fromdincontext.Departments
whered.DeptName==DepartmentNames.Computer
selectd
).FirstOrDefault();
Console.WriteLine(
"DepartmentID:{0},DepartmentName:{1}",
department.DeptID,department.DeptName
);
Console.ReadKey();
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

120/225

8/12/2016

EntityFrameworkQuickGuide

}
}

Whentheabovecodeisexecuted,youwillreceivethefollowingoutput
DepartmentID:2,DepartmentName:Computer

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKASYNCHRONOUSQUERY
Asynchronousprogramminginvolvesexecutingoperationsinthebackgroundsothatthemainthreadcan
continueitsownoperations.Thiswaythemainthreadcankeeptheuserinterfaceresponsivewhilethe
backgroundthreadisprocessingthetaskathand.
EntityFramework6.0supportsasynchronousoperationsforqueryingandsavingofdata.
Asynchronousoperationscanhelpyourapplicationinthefollowingways
Makeyourapplicationmoreresponsivetouserinteractions
Improvetheoverallperformanceofyourapplication
Youcanexecuteasynchronousoperationsinvariousways.Butasync/awaitkeywordswereintroducedin
.NETFramework4.5whichmakesyourjobsimple.
Theonlythingyouneedtofollowistheasync/awaitpatternasillustratedbythefollowingcodefragment.
Letstakealookatthefollowingexamplewithoutusingasync/awaitinwhichDatabaseOperationsmethodsaves
anewstudenttothedatabaseandthenretrievesallstudentsfromthedatabaseandattheendsomeadditional
messageisprintedontheconsole.
classProgram{
staticvoidMain(string[]args){
Console.WriteLine("DatabaseOperationsStarted");
DatabaseOperations();

Console.WriteLine();
Console.WriteLine("DatabaseOperationsCompleted");
Console.WriteLine();
Console.WriteLine("EntityFrameworkTutorials");
Console.ReadKey();
}
publicstaticvoidDatabaseOperations(){
using(varcontext=newUniContextEntities()){
//Createanewstudentandsaveit
context.Students.Add(newStudent{
FirstMidName="Akram",
LastName="Khan",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())});
Console.WriteLine("CallingSaveChanges.");
context.SaveChanges();
Console.WriteLine("SaveChangescompleted.");

http://www.tutorialspoint.com/cgibin/printpage.cgi

121/225

8/12/2016

EntityFrameworkQuickGuide

//QueryforallStudentsorderedbyfirstname
varstudents=(fromsincontext.Students
orderbys.FirstMidNameselects).ToList();
//WriteallstudentsouttoConsole
Console.WriteLine();
Console.WriteLine("AllStudent:");
foreach(varstudentinstudents){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine(""+name);
}
}
}
}

Whentheabovecodeisexecuted,youwillreceivethefollowingoutput
CallingSaveChanges.
SaveChangescompleted.
AllStudent:
AkramKhan
AliKhan
AliAlexander
ArturoAnand
BillGates
GytisBarzdukas
LauraNornan
Meredithfllonso
NinoOlioetto
PeggyJustice
YanLi
EntityFrameworkTutorials

LetsusethenewasyncandawaitkeywordsandmakethefollowingchangestoProgram.cs
AddSystem.Data.EntitynamespacewhichwillgiveEFasyncextensionmethods.
AddSystem.Threading.TasksnamespacewhichwillallowustousetheTasktype.
UpdateDatabaseOperationstobemarkedasasyncandreturnaTask.
CalltheAsyncversionofSaveChangesandawaititscompletion.
CalltheAsyncversionofToListandawaittheresult.
classProgram{
staticvoidMain(string[]args){
vartask=DatabaseOperations();
Console.WriteLine();
Console.WriteLine("EntityFrameworkTutorials");
task.Wait();
Console.ReadKey();
}
publicstaticasyncTaskDatabaseOperations(){

http://www.tutorialspoint.com/cgibin/printpage.cgi

122/225

8/12/2016

EntityFrameworkQuickGuide

using(varcontext=newUniContextEntities()){
//Createanewblogandsaveit
context.Students.Add(newStudent{
FirstMidName="Salman",
LastName="Khan",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())});
Console.WriteLine("CallingSaveChanges.");
awaitcontext.SaveChangesAsync();
Console.WriteLine("SaveChangescompleted.");
//QueryforallStudentsorderedbyfirstname
varstudents=await(fromsincontext.Students
orderbys.FirstMidNameselects).ToListAsync();
//WriteallstudentsouttoConsole
Console.WriteLine();
Console.WriteLine("AllStudent:");
foreach(varstudentinstudents){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine(""+name);
}
}
}
}

Onexecution,itwillproducethefollowingoutput.
CallingSaveChanges.
EntityFrameworkTutorials
SaveChangescompleted.
AllStudent:
AkramKhan
AliKhan
AliAlexander
ArturoAnand
BillGates
GytisBarzdukas
LauraNornan
Meredithfllonso
NinoOlioetto
PeggyJustice
SalmanKhan
YanLi

Nowthatthecodeisasynchronous,youcanobserveadifferentexecutionflowofyourprogram.
SaveChangesbeginstopushthenewStudenttothedatabaseandthentheDatabaseOperationsmethod
returnseventhoughithasn tf inishedexecutingandprogramflowintheMainmethodcontinues.

Messageisthenwrittentotheconsole.
ThemanagedthreadisblockedontheWaitcalluntilthedatabaseoperationcompletes.Onceit
completes,theremainderofourDatabaseOperationswillbeexecuted.

http://www.tutorialspoint.com/cgibin/printpage.cgi

123/225

8/12/2016

EntityFrameworkQuickGuide

SaveChangescompletes.
RetrievedallthestudentfromthedatabaseandiswrittentotheConsole.
Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKPERSISTENCE
EntityFrameworknowallowsyoutobenefitfromtheEntityFrameworkwithoutforcingeverypartofyour
applicationtobeawareoftheEntityFramework,separatingentitiesfromtheinfrastructure.Youcancreate
classesthatcanfocusontheirbusinessruleswithoutregardtohowtheyarepersisted
wherethedataisstoredandhowthedatagetsbackandf orthbetweenyourobjects.

CreatingPersistentIgnorantEntities
Theprecedingparagraphdescribedamethodthathasnointimateknowledgeofthesourceofthedatait
consumes.Thishighlightstheessenceofpersistenceignorance,whichiswhenyourclassesandmanyofour
applicationlayersaroundthemdontcarehowthedataisstored.
Inthe.NET3.5versionofEntityFramework,ifyouwantedtousepreexistingclasses,youwererequired
tomodifythembyforcingthemtoderivefromEntityObject.
In.NET4thisisnolongernecessary.Youdonthavetomodifyyourentitiesinorderforthemto
participateinEntityFrameworkoperations.
Thisallowsustobuildapplicationsthatembraceloosecouplingandseparationofconcerns.
Withthesecodingpatterns,yourclassesareonlyconcernedwiththeirownjobsand,manylayersofyour
application,includingtheUI,havenodependenciesonexternallogic,suchastheEntityFrameworkAPIs,
yetthoseexternalAPIsareabletointeractwithourentities.
Thereare2waysconnectedanddisconnectedwhenpersistinganentitywiththeEntityFramework.Bothways
havetheirownimportance.Inthecaseofaconnectedscenariothechangesaretrackedbythecontextbutinthe
caseofadisconnectedscenarioweneedtoinformthecontextaboutthestateoftheentity.

ConnectedScenarios
Connectedscenarioiswhenanentityisretrievedfromthedatabaseandmodifiedinthesamecontext.Fora
connectedscenarioletussupposewehaveaWindowsserviceandwearedoingsomebusinessoperationswith
thatentitysowewillopenthecontext,loopthroughalltheentities,doourbusinessoperationsandthensave
thechangeswiththesamecontextthatweopenedinthebeginning.
Letstakealookatthefollowingexampleinwhichstudentsareretrievedfromdatabaseandupdatethe
studentsfirstnameandthensavechangestothedatabase.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newMyContext()){
varstudentList=context.Students.ToList();
foreach(varstdntinstudentList){
stdnt.FirstMidName="Edited"+stdnt.FirstMidName;
}
context.SaveChanges();

http://www.tutorialspoint.com/cgibin/printpage.cgi

124/225

8/12/2016

EntityFrameworkQuickGuide

////DisplayallStudentsfromthedatabase
varstudents=(fromsincontext.Students
orderbys.FirstMidNameselects).ToList<Student>();
Console.WriteLine("RetrieveallStudentsfromthedatabase:");
foreach(varstdntinstudents){
stringname=stdnt.FirstMidName+""+stdnt.LastName;
Console.WriteLine("ID:{0},Name:{1}",stdnt.ID,name);
}
Console.ReadKey();
}
}
}

WhentheabovecodeiscompiledandexecutedyouwillreceivethefollowingoutputandyouwillseethatEdited
wordisattachedbeforethefirstnameasshowninthefollowingoutput.
RetrieveallStudentsfromthedatabase:
ID:1,Name:EditedEditedAlainBomer
ID:2,Name:EditedEditedMarkUpston

DisconnectedScenarios
Disconnectedscenarioiswhenanentityisretrievedfromthedatabaseandmodifiedinthedifferentcontext.
Let'ssupposewewanttodisplaysomedatainaPresentationLayerandweareusingsomentierapplication,so
itwouldbebettertoopenthecontext,fetchthedataandfinallyclosethecontext.Sinceherewehavefetched
thedataandclosedthecontext,theentitiesthatwehavefetchedarenolongertrackedandthisisthe
disconnectedscenario.
LetstakealookatthefollowingcodeinwhichnewdisconnectedStudententityisaddedtoacontextusingthe
Addmethod.
classProgram{
staticvoidMain(string[]args){
varstudent=newStudent{
ID=1001,
FirstMidName="Wasim",
LastName="Akram",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
};
using(varcontext=newMyContext()){
context.Students.Add(student);
context.SaveChanges();
////DisplayallStudentsfromthedatabase
varstudents=(fromsincontext.Students
orderbys.FirstMidNameselects).ToList<Student>();
Console.WriteLine("RetrieveallStudentsfromthedatabase:");
foreach(varstdntinstudents){
stringname=stdnt.FirstMidName+""+stdnt.LastName;

http://www.tutorialspoint.com/cgibin/printpage.cgi

125/225

8/12/2016

EntityFrameworkQuickGuide

Console.WriteLine("ID:{0},Name:{1}",stdnt.ID,name);
}
Console.ReadKey();
}
}
}

Whentheabovecodeiscompiledandexecuted,youwillreceivethefollowingoutput.
RetrieveallStudentsfromthedatabase:
ID:1,Name:EditedEditedEditedAlainBomer
ID:2,Name:EditedEditedEditedMarkUpston
ID:3,Name:WasimAkram

ENTITYFRAMEWORKPROJECTIONQUERIES
LINQtoEntities
OneofthemostimportantconceptstounderstandLINQtoEntitiesisthatitsadeclarativelanguage.Thefocus
isondefiningwhatinformationyouneed,ratherthanonhowtoobtaintheinformation.
Itmeansthatyoucanspendmoretimeworkingwithdataandlesstimetryingtofigureouttheunderlying
coderequiredtoperformtaskssuchasaccessingthedatabase.
Itsimportanttounderstandthatdeclarativelanguagesdontactuallyremoveanycontrolfromthe
developer,butithelpsthedeveloperfocusattentiononwhatsimportant.

LINQtoEntitiesEssentialKeywords
ItsimportanttoknowthebasickeywordsusedtocreateaLINQquery.Thereareonlyafewkeywordsto
remember,butyoucancombinetheminvariouswaystoobtainspecificresults.Thefollowinglistcontainsthese
basickeywordsandprovidesasimpledescriptionofeachone.

Sr.No.
1

Keyword&Description
Ascending
Specifiesthatasortingoperationtakesplacefromtheleastorlowestelementofarangetothe
highestelementofarange.Thisisnormallythedefaultsetting.Forexample,whenperforming
analphabeticsort,thesortwouldbeintherangefromAtoZ.

By
Specifiesthefieldorexpressionusedtoimplementagrouping.Thefieldorexpressiondefines
akeyusedtoperformthegroupingtask.

Descending
Specifiesthatasortingoperationtakesplacefromthegreatestorhighestelementofarangeto
thelowestelementofarange.Forexample,whenperforminganalphabeticsort,thesort

http://www.tutorialspoint.com/cgibin/printpage.cgi

126/225

8/12/2016

EntityFrameworkQuickGuide

wouldbeintherangefromZtoA.
4

Equals
Usedbetweentheleftandrightclausesofajoinstatementtojointheprimarycontextualdata
sourcetothesecondarycontextualdatasource.Thefieldorexpressionontheleftofthe
equalskeywordspecifiestheprimarydatasource,whilethefieldorexpressionontherightof
theequalskeywordspecifiesthesecondarydatasource.

From
Specifiesthedatasourceusedtoobtaintherequiredinformationanddefinesarangevariable.
Thisvariablehasthesamepurposeasavariableusedforiterationinaloop.

Group
Organizestheoutputintogroupsusingthekeyvalueyouspecify.Usemultiplegroupclauses
tocreatemultiplelevelsofoutputorganization.Theorderofthegroupclausesdeterminesthe
depthatwhichaparticularkeyvalueappearsinthegroupingorder.Youcombinethiskeyword
withbytocreateaspecificcontext.

In
Usedinanumberofways.Inthiscase,thekeyworddeterminesthecontextualdatabase
sourceusedforaquery.Whenworkingwithajoin,theinkeywordisusedforeachcontextual
databasesourceusedforthejoin.

Into
SpecifiesanidentifierthatyoucanuseasareferenceforLINQqueryclausessuchasjoin,
group,andselect.

Join
Createsasingledatasourcefromtworelateddatasources,suchasinamaster/detailsetup.A
joincanspecifyaninner,group,orleftouterjoin,withtheinnerjoinasthedefault.Youcan
readmoreaboutjoinsatmsdn.microsoft.com

10

Let

http://www.tutorialspoint.com/cgibin/printpage.cgi

127/225

8/12/2016

EntityFrameworkQuickGuide

Definesarangevariablethatyoucanusetostoresubexpressionresultsinaqueryexpression.
Typically,therangevariableisusedtoprovideanadditionalenumeratedoutputortoincrease
theefficiencyofaquerysothataparticulartask, suchasf indingthelowercasevalueof astring, .
neednotbedonemorethanonetime

11

On
Specifiesthefieldorexpressionusedtoimplementajoin.Thefieldorexpressiondefinesan
elementthatiscommontobothcontextualdatasources.

12

Orderby
Createsasortorderforthequery.Youcanaddtheascendingordescendingkeywordto
controltheorderofthesort.Usemultipleorderbyclausestocreatemultiplelevelsofsorting.
Theorderoftheorderbyclausesdeterminestheorderinwhichthesortexpressionsare
handled,sousingadifferentorderwillresultindifferentoutput.

13

Where
DefineswhatLINQshouldretrievefromthedatasource.YouuseoneormoreBoolean
expressionstodefinethespecificsofwhattoretrieve.TheBooleanexpressionsareseparated
fromeachotherusingthe&&AN Dand||ORoperators.

14

Select
DeterminestheoutputfromtheLINQquerybyspecifyingwhatinformationtoreturn.This
statementdefinesthedatatypeoftheelementsthatLINQreturnsduringtheiteration
process.

Projection
Projectionqueriesimprovetheefficiencyofyourapplication,byonlyretrievingspecificfieldsfromyour
database.
Onceyouhavethedata,youmaywanttoprojectorfilteritasneededtoshapethedatapriortooutput.
ThemaintaskofanyLINQtoEntitiesexpressionistoobtaindataandprovideitasoutput.
TheDevelopingLINQtoEntitiesqueriessectionofthischapterdemonstratesthetechniquesforperforming
thisbasictask.
Letstakealookatthefollowingcodeinwhichlistofstudentswillberetrieved.
using(varcontext=newUniContextEntities()){

http://www.tutorialspoint.com/cgibin/printpage.cgi

128/225

8/12/2016

EntityFrameworkQuickGuide

varstudentList=fromsincontext.Studentsselects;
foreach(varstudentinstudentList){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
}
}

SingleObject
ToretrieveasinglestudentobjectyoucanuseFirstorFirstOrDefaultenumerablemethodswhichreturnsthe
firstelementofasequence.ThedifferencebetweenFirstandFirstOrDefaultisthatFirstwillthrowan
exception,ifthereisnoresultdataforthesuppliedcriteriawhereasFirstOrDefaultreturnsdefaultvaluenull,if
thereisnoresultdata.Inthebelowcodesnippetfirststudentfromthelistwillberetrievedwhosefirstnameis
Ali.
using(varcontext=newUniContextEntities()){
varstudent=(fromsincontext.Studentswheres.FirstMidName
=="Ali"selects).FirstOrDefault<Student>();
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
}

YoucanalsouseSingleorSingleOrDefaulttogetasinglestudentobjectwhichreturnsasingle,specificelement
ofasequence.Inthefollowingexample,asinglestudentisretrievedwhoseIDis2.
using(varcontext=newUniContextEntities()){
varstudent=(fromsincontext.Studentswheres.ID
==2selects).SingleOrDefault<Student>();
stringname=student.FirstMidName+""+student.LastName;

Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
Console.ReadKey();
}

ListofObjects
IfyouwanttoretrievethelistofstudentswhosefirstnameisAlithenyoucanuseToListenumerablemethod.
using(varcontext=newUniContextEntities()){
varstudentList=(fromsincontext.Studentswheres.FirstMidName
=="Ali"selects).ToList();
foreach(varstudentinstudentList){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
}
Console.ReadKey();
}

Order
Toretrievedata/listinanyparticularorderyoucanusedorderbykeyword.Inthefollowingcode,snippetlistof
studentwillberetrievedinascendingorder.

http://www.tutorialspoint.com/cgibin/printpage.cgi

129/225

8/12/2016

EntityFrameworkQuickGuide

using(varcontext=newUniContextEntities()){
varstudentList=(fromsincontext.Studentsorderby
s.FirstMidNameascendingselects).ToList();
foreach(varstudentinstudentList){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
}
Console.ReadKey();
}

StandardVsProjectionEntityFrameworkQuery
Letssuppose,youhaveaStudentmodelthatcontainstheID,FirstMidName,LastNameandEnrollmentDate.If
youwanttoreturnalistofStudents,astandardquerywouldreturnallthefields.Butifyouonlywanttogeta
listofstudentsthatcontainID,FirstMidName,andLastNamefields.Thisiswhereyoushoulduseaprojection
query.Followingisthesimpleexampleofprojectionquery.
using(varcontext=newUniContextEntities()){
varstudentList=fromsincontext.Students
orderbys.FirstMidNameascending
wheres.FirstMidName=="Ali"
selectnew{s.ID,s.FirstMidName,s.LastName};
foreach(varstudentinstudentList){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
}
Console.ReadKey();
}

TheprojectionqueryaboveexcludestheEnrollmentDatefield.Thiswillmakeyourapplicationmuchquicker.

ENTITYFRAMEWORKCOMMANDLOGGING
InEntityFramework6.0,anewfeatureisintroducedwhichisknownasLoggingSQL.Whileworkingwith
EntityFramework,itsendscommandsoranequivalentSQLquerytothedatabasetodoaCRUD
C reate, Read, U pdate, andDelete operations.
ThisfeatureoftheEntityFrameworkistocaptureanequivalentSQLquerygeneratedbyEntity
Frameworkinternallyandprovideitasoutput.
BeforeEntityFramework6,whenevertherewasaneedtotracedatabasequeriesandcommand,the
developerhadnooptionbuttousesomethirdpartytracingutilityordatabasetracingtool.
InEntityFramework6,thisnewfeatureprovidesasimplewaybyloggingalltheoperationsperformedby
EntityFramework.
AlltheactivitieswhichareperformedbyEntityFrameworkareloggedusingDbContext.Database.Log.
Letstakealookatthefollowingcodeinwhichanewstudentisaddedtothedatabase.

http://www.tutorialspoint.com/cgibin/printpage.cgi

130/225

8/12/2016

EntityFrameworkQuickGuide

classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
context.Database.Log=Console.Write;
//Createanewstudentandsaveit
context.Students.Add(newStudent{
FirstMidName="Salman",
LastName="Khan",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
});
context.SaveChanges();
Console.ReadKey();
}
}
}

Whentheabovecodeisexecuted,youwillreceivethefollowingoutput,whichisactuallythelogofallthe
activitiesperformedbyEFintheabovecode.
Openedconnectionat10/28/20156:27:35PM+05:00
Startedtransactionat10/28/20156:27:35PM+05:00
INSERT[dbo].[Student]([LastName],[FirstMidName],[EnrollmentDate])
VALUES(@0,@1,@2)
SELECT[ID]
FROM[dbo].[Student]
WHERE@@ROWCOUNT>0AND[ID]=scope_identity()
@0:'Khan'(Type=String,Size=1)
@1:'Salman'(Type=String,Size=1)
@2:'10/28/201512:00:00AM'(Type=DateTime)
Executingat10/28/20156:27:35PM+05:00
Completedin5mswithresult:SqlDataReader
Committedtransactionat10/28/20156:27:35PM+05:00
Closedconnectionat10/28/20156:27:35PM+05:00

WhentheLogpropertyissetthefollowingactivitiesarelogged
SQLforalldifferentkindsofcommandse.g.Queries,includinginserts,updates,anddeletesgeneratedas
partofSaveChanges
Parameters
Whetherornotthecommandisbeingexecutedasynchronously
Atimestampindicatingwhenthecommandstartedexecuting
Thecommandcompletedsuccessfullyorfailed
Someindicationoftheresultvalue
Theapproximateamountoftimeittooktoexecutethecommand

LoggingtoOtherPlace

http://www.tutorialspoint.com/cgibin/printpage.cgi

131/225

8/12/2016

EntityFrameworkQuickGuide

Ifyoualreadyhavesomeloggingframeworkanditdefinesaloggingmethodthenyoucanalsologittoother
place.
LetstakealookatthefollowingexampleinwhichwehaveanotherclassMyLogger.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
context.Database.Log=sMyLogger.Log("EFLoggingDemo",s);
//Createanewstudentandsaveit
context.Students.Add(newStudent{
FirstMidName="Salman",
LastName="Khan",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
});
context.SaveChanges();
Console.ReadKey();
}
}
}
publicclassMyLogger{
publicstaticvoidLog(stringapplication,stringmessage){
Console.WriteLine("Application:{0},EFMessage:{1}",application,message);
}
}

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKCOMMANDINTERCEPTION
InEntityFramework6.0,thereisanothernewfeatureknownasInterceptororInterception.Theinterception
codeisbuiltaroundtheconceptofinterceptioninterfaces.Forexample,theIDbCommandInterceptor
interfacedefinesmethodsthatarecalledbeforeEFmakesacalltoExecuteNonQuery,ExecuteScalar,
ExecuteReader,andrelatedmethods.
EntityFrameworkcantrulyshinebyusinginterception.Usingthisapproachyoucancapturealotmore
informationtransientlywithouthavingtountidyyourcode.
Toimplementthis,youneedtocreateyourowncustominterceptorandregisteritaccordingly.
OnceaclassthatimplementsIDbCommandInterceptorinterfacehasbeencreateditcanberegistered
withEntityFrameworkusingtheDbInterceptionclass.
IDbCommandInterceptorinterfacehassixmethodsandyouneedtoimplementallthesemethods.
Followingarethebasicimplementationofthesemethods.
LetstakealookatthefollowingcodeinwhichIDbCommandInterceptorinterfaceisimplemented.
publicclassMyCommandInterceptor:IDbCommandInterceptor{
publicstaticvoidLog(stringcomm,stringmessage){

http://www.tutorialspoint.com/cgibin/printpage.cgi

132/225

8/12/2016

EntityFrameworkQuickGuide

Console.WriteLine("Intercepted:{0},CommandText:{1}",comm,message);
}
publicvoidNonQueryExecuted(DbCommandcommand,
DbCommandInterceptionContext<int>interceptionContext){
Log("NonQueryExecuted:",command.CommandText);
}
publicvoidNonQueryExecuting(DbCommandcommand,
DbCommandInterceptionContext<int>interceptionContext){
Log("NonQueryExecuting:",command.CommandText);
}
publicvoidReaderExecuted(DbCommandcommand,
DbCommandInterceptionContext<DbDataReader>interceptionContext){
Log("ReaderExecuted:",command.CommandText);
}
publicvoidReaderExecuting(DbCommandcommand,
DbCommandInterceptionContext<DbDataReader>interceptionContext){
Log("ReaderExecuting:",command.CommandText);
}
publicvoidScalarExecuted(DbCommandcommand,
DbCommandInterceptionContext<object>interceptionContext){
Log("ScalarExecuted:",command.CommandText);
}
publicvoidScalarExecuting(DbCommandcommand,
DbCommandInterceptionContext<object>interceptionContext){
Log("ScalarExecuting:",command.CommandText);
}
}

RegisteringInterceptors
Onceaclassthatimplementsoneormoreoftheinterceptioninterfaceshasbeencreateditcanberegistered
withEFusingtheDbInterceptionclassasshowninthefollowingcode.
DbInterception.Add(newMyCommandInterceptor());

InterceptorscanalsoberegisteredattheappdomainlevelusingtheDbConfigurationcodebasedconfiguration
asshowninthefollowingcode.
publicclassMyDBConfiguration:DbConfiguration{
publicMyDBConfiguration(){
DbInterception.Add(newMyCommandInterceptor());
}
}

Youcanalsoconfigureinterceptorconfigfileusingthecode
<entityFramework>
<interceptors>
<interceptortype="EFInterceptDemo.MyCommandInterceptor,EFInterceptDemo"/>
</interceptors>
</entityFramework>

ENTITYFRAMEWORKSPATIALDATATYPE
http://www.tutorialspoint.com/cgibin/printpage.cgi

133/225

8/12/2016

EntityFrameworkQuickGuide

ENTITYFRAMEWORKSPATIALDATATYPE
SpatialtypesupportwasintroducedinEntityFramework5.Asetofoperatorsisalsoincludedtoallowqueries
toanalyzespatialdata.Forexample,aquerycanfilterbasedonthedistancebetweentwogeographiclocations.
EntityFrameworkwillallownewspatialdatatypestobeexposedaspropertiesonyourclassesandmap
themtospatialcolumnsinyourdatabase.
YouwillalsobeabletowriteLINQqueriesthatmakeuseofthespatialoperatorstofilter,sort,andgroup
basedonspatialcalculationsperformedinthedatabase.
Therearetwomainspatialdatatypes
Thegeographydatatypestoresellipsoidaldata,forexample,GPSlatitudeandlongitudecoordinates.
ThegeometrydatatyperepresentsEuclideanf latcoordinatesystem.
LetstakealookintothefollowingexampleofCricketground.
Step1CreatenewprojectfromFileNewProjectmenuoption.
Step2Intheleftpane,selecttheConsoleApplication.

Step3RightclickonprojectnameandselectManageNuGetPackages

http://www.tutorialspoint.com/cgibin/printpage.cgi

134/225

8/12/2016

EntityFrameworkQuickGuide

Step4InstallEntityFramework.
Step5AddreferencetoSystem.Data.EntityassemblyandalsoaddtheSystem.Data.Spatialusingstatement
forspatialdatatypes.

http://www.tutorialspoint.com/cgibin/printpage.cgi

135/225

8/12/2016

EntityFrameworkQuickGuide

Step6AddthefollowingclassinProgram.csfile.
publicclassCricketGround{
publicintID{get;set;}
publicstringName{get;set;}
publicDbGeographyLocation{get;set;}
}

Step7Inadditiontodefiningentities,youneedtodefineaclassthatderivesfromDbContextandexposes
DbSet<TEntity>properties.
IntheProgram.csaddthecontextdefinition.
publicpartialclassCricketGroundContext:DbContext{
publicDbSet<CricketGround>CricketGrounds{get;set;}
}

Step8AddthefollowingcodeintotheMainfunction,whichwilladdtwonewCricketGroundobjectstothe
context.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newCricketGroundContext()){
context.CricketGrounds.Add(newCricketGround(){
Name="ShalimarCricketGround",
Location=DbGeography.FromText("POINT(122.33610647.605049)"),
});
context.CricketGrounds.Add(newCricketGround(){

http://www.tutorialspoint.com/cgibin/printpage.cgi

136/225

8/12/2016

EntityFrameworkQuickGuide

Name="MarghazarStadium",Location=DbGeography
.FromText("POINT(122.33519747.646711)"),
});
context.SaveChanges();
varmyLocation=DbGeography.FromText("POINT(122.29662347.640405)");
varcricketGround=(fromcgincontext.CricketGrounds
orderbycg.Location.Distance(myLocation)selectcg).FirstOrDefault();
Console.WriteLine("TheclosestCricketGroundtoyouis:{0}.",cricketGround.Name);
}
}
}

SpatialpropertiesareinitializedbyusingtheDbGeography.FromTextmethod.Thegeographypoint
representedasWellKnownTextispassedtothemethodandthensavesthedata.AfterthatCricketGround
objectwillberetrievedwhereitslocationisclosesttothespecifiedlocation.
Whentheabovecodeisexecuted,youwillreceivethefollowingoutput
TheclosestCricketGroundtoyouis:MarghazarStadium

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKINHERITANCE
Inheritancemakesitpossibletocreatecomplexmodelsthatbetterreflecthowdevelopersthinkandalsoreduce
theworkrequiredtointeractwiththosemodels.Inheritanceusedwithentitiesservesthesamepurposeas
inheritanceusedwithclasses,sodevelopersalreadyknowthebasicsofhowthisfeatureworks.
Letstakealookatthefollowingexampleandbycreatinganewconsoleapplicationproject.
Step1AddADO.NETEntityDataModelbyrightclickingonprojectnameandselectAddNewItem
Step2AddoneentityandnameitPersonbyfollowingallthestepsmentionedinthechapterModelFirst
approach.
Step3Addsomescalarpropertiesasshowninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

137/225

8/12/2016

EntityFrameworkQuickGuide

Step4WewilladdtwomoreentitiesStudentandTeacher,whichwillinheritthepropertiesfromPerson
Table.
Step5NowaddStudententityandselectPersonfromtheBasetypecomboboxasshowninthefollowing
image.

http://www.tutorialspoint.com/cgibin/printpage.cgi

138/225

8/12/2016

EntityFrameworkQuickGuide

Step6SimilarlyaddTeacherentity.
Step7NowaddEnrollmentDatescalarpropertytostudententityandHireDatepropertytoTeacherentity.

http://www.tutorialspoint.com/cgibin/printpage.cgi

139/225

8/12/2016

EntityFrameworkQuickGuide

Step8Let'sgoaheadandgeneratethedatabase.
Step9RightclickonthedesignsurfaceandselectGenerateDatabasefromModel

http://www.tutorialspoint.com/cgibin/printpage.cgi

140/225

8/12/2016

EntityFrameworkQuickGuide

Step10TocreatenewDatabaseclickonNewConnectionThefollowingdialogwillopen.ClickOK.

http://www.tutorialspoint.com/cgibin/printpage.cgi

141/225

8/12/2016

EntityFrameworkQuickGuide

Step11ClickFinish.Thiswilladd*.edmx.sqlfileintheproject.YoucanexecuteDDLscriptsinVisualStudio
byopening.sqlfile.NowrightclickandselectExecute.
Step12Gototheserverexploreryouwillseethatthedatabaseiscreatedwiththreetableswhichare
specified.

http://www.tutorialspoint.com/cgibin/printpage.cgi

142/225

8/12/2016

EntityFrameworkQuickGuide

Step13Youcanalsoseethatthefollowingdomainclassesarealsogeneratedautomatically.
publicpartialclassPerson{
publicintID{get;set;}
publicstringFirstMidName{get;set;}
publicstringLastName{get;set;}
}
publicpartialclassStudent:Person{
publicSystem.DateTimeEnrollmentDate{get;set;}
}
publicpartialclassTeacher:Person{
publicSystem.DateTimeHireDate{get;set;}
}

FollowingistheContextclass.
publicpartialclassInheritanceModelContainer:DbContext{
publicInheritanceModelContainer():
base("name=InheritanceModelContainer"){}
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
thrownewUnintentionalCodeFirstException();
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

143/225

8/12/2016

EntityFrameworkQuickGuide

publicvirtualDbSet<Person>People{get;set;}
}

LetsaddsomeStudentsandTeacherstothedatabaseandthenretrieveitfromthedatabase.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newInheritanceModelContainer()){
varstudent=newStudent{
FirstMidName="Meredith",
LastName="Alonso",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
};
context.People.Add(student);
varstudent1=newStudent{
FirstMidName="Arturo",
LastName="Anand",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
};
context.People.Add(student1);
vartechaer=newTeacher{
FirstMidName="Peggy",
LastName="Justice",
HireDate=DateTime.Parse(DateTime.Today.ToString())
};
context.People.Add(techaer);
vartechaer1=newTeacher{
FirstMidName="Yan",
LastName="Li",
HireDate=DateTime.Parse(DateTime.Today.ToString())
};
context.People.Add(techaer1);
context.SaveChanges();
}
}
}

Studentsandteachersareaddedinthedatabase.NToretrievestudentsandteacher,theOfTypemethodneeds
tobeused,whichwillreturnStudentandTeacherrelatedtothespecifieddepartment.
Console.WriteLine("Allstudentsindatabase");
Console.WriteLine("");
foreach(varstudentincontext.People.OfType<Student>()){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1},\tEnrollmentDate{2}",
student.ID,name,student.EnrollmentDate.ToString());
}
Console.WriteLine("");
Console.WriteLine("*****************************************************************");

http://www.tutorialspoint.com/cgibin/printpage.cgi

144/225

8/12/2016

EntityFrameworkQuickGuide

Console.WriteLine("");
Console.WriteLine("Allteachersindatabase");
Console.WriteLine("");
foreach(varteacherincontext.People.OfType<Teacher>()){
stringname=teacher.FirstMidName+""+teacher.LastName;
Console.WriteLine("ID:{0},Name:{1},\tHireDate{2}",
teacher.ID,name,teacher.HireDate.ToString());
}
Console.WriteLine("");
Console.WriteLine("*****************************************************************");
Console.ReadKey();

Inthefirstquery,whenyouuseOfType<Student>thenyouwillnotbeabletoaccessHireDatebecause
HireDatepropertyispartofTeacherEntityandsimilarlyEnrollmentDatepropertywillnotbeaccessiblewhen
youuseOfType<Teacher>
Whentheabovecodeisexecuted,youwillreceivethefollowingoutput
Allstudentsindatabase
ID:1,Name:MeredithAlonso,EnrollmentDate10/30/201512:00:00AM
ID:2,Name:ArturoAnand,EnrollmentDate10/30/201512:00:00AM
*****************************************************************
Allteachersindatabase
ID:3,Name:PeggyJustice,HireDate10/30/201512:00:00AM
ID:4,Name:YanLi,HireDate10/30/201512:00:00AM
*****************************************************************

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKMIGRATION
InEntityFramework5andpreviousversionsofEntityFramework,thecodewassplitbetweencorelibraries
primarilyS ystem. Data. Entity. dll shippedaspartofthe.NETFramework,andtheadditionallibraries
primarilyEntityF ramework. dll wasdistributedandshippedusingNuGetasshowninthefollowingdiagram.

http://www.tutorialspoint.com/cgibin/printpage.cgi

145/225

8/12/2016

EntityFrameworkQuickGuide

InEntityFramework6,thecoreAPIswhichwerepreviouslypartof.NETframeworkarealsoshippedand
distributedasapartofNuGetpackage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

146/225

8/12/2016

EntityFrameworkQuickGuide

ThiswasnecessarytoallowEntityFrameworktobemadeopensource.However,asaconsequenceapplications
willneedtoberebuiltwheneverthereisaneedtomigrateorupgradeyourapplicationfromolderversionsof
EntityFrameworktoEF6.
ThemigrationprocessisstraightforwardifyourapplicationusesDbContext,whichwasshippedinEF4.1and
later.ButifyourapplicationisObjectContextthenlittlemoreworkisrequired.
LetstakealookatthefollowingstepsyouneedtogothroughtoupgradeanexistingapplicationtoEF6.
Step1Thefirststepistotarget.NETFramework4.5.2andlaterrightclickonyourprojectandselect
properties.

http://www.tutorialspoint.com/cgibin/printpage.cgi

147/225

8/12/2016

EntityFrameworkQuickGuide

Step2RightclickonyourprojectagainandselectManageNuGetPackages...

http://www.tutorialspoint.com/cgibin/printpage.cgi

148/225

8/12/2016

EntityFrameworkQuickGuide

Step3UndertheOnlinetabselectEntityFrameworkandclickInstall.Makesurethatassemblyreferencesto
System.Data.Entity.dllareremoved.
WhenyouinstallEF6NuGetpackageitshouldautomaticallyremoveanyreferencestoSystem.Data.Entityfrom
yourprojectforyou.
Step4IfyouhaveanymodelwhichiscreatedwiththeEFDesigner,thenyouwillalsoneedtoupdatethe
codegenerationtemplatestogenerateEF6compatiblecode.
Step5InyourSolutionExplorerunderyouredmxfile,deleteexistingcodegenerationtemplateswhich
typicallywillbenamed<edmx_file_name>.ttand<edmx_file_name>.Context.tt.

http://www.tutorialspoint.com/cgibin/printpage.cgi

149/225

8/12/2016

EntityFrameworkQuickGuide

Step6OpenyourmodelintheEFDesigner,rightclickonthedesignsurfaceandselectAddCodeGeneration
Item...
Step7AddtheappropriateEF6.xcodegenerationtemplate.

http://www.tutorialspoint.com/cgibin/printpage.cgi

150/225

8/12/2016

EntityFrameworkQuickGuide

ItwillalsogenerateEF6compatiblecodeautomatically.
IfyourapplicationsuseEF4.1orlateryouwillnotneedtochangeanythinginthecode,becausethenamespaces
forDbContextandCodeFirsttypeshavenotchanged.
ButifyourapplicationisusingolderversionofEntityFrameworkthentypeslikeObjectContextthatwere
previouslyinSystem.Data.Entity.dllhavebeenmovedtonewnamespaces.
Step8YouwillneedtoupdateyourusingorImportdirectivestobuildagainstEF6.
ThegeneralrulefornamespacechangesisthatanytypeinSystem.Data.*ismovedto
System.Data.Entity.Core.*.Followingaresomeofthem
System.Data.EntityExceptionSystem.Data.Entity.Core.EntityException
System.Data.Objects.ObjectContextSystem.Data.Entity.Core.Objects.ObjectContext
System.Data.Objects.DataClasses.RelationshipManager
System.Data.Entity.Core.Objects.DataClasses.RelationshipManager
SometypesareintheCorenamespacesbecausetheyarenotuseddirectlyformostDbContextbased
applications.
System.Data.EntityStateSystem.Data.Entity.EntityState
System.Data.Objects.DataClasses.EdmFunctionAttributeSystem.Data.Entity.DbFunctionAttribute
YourexistingEntityFrameworkprojectwillworkinEntityFramework6.0withoutanymajorchanges.

ENTITYFRAMEWORKEAGERLOADING

http://www.tutorialspoint.com/cgibin/printpage.cgi

151/225

8/12/2016

EntityFrameworkQuickGuide

Eagerloadingistheprocesswherebyaqueryforonetypeofentityalsoloadsrelatedentitiesaspartofthe
query.EagerloadingisachievedbytheuseoftheIncludemethod.
Itmeansthatrequestingrelateddatabereturnedalongwithqueryresultsfromthedatabase.Thereisonlyone
connectionmadetothedatasource,alargeramountofdataisreturnedintheinitialquery.
Forexample,whenqueryingstudents,eagerloadtheirenrollments.Thestudentsandtheirenrollmentswillbe
retrievedinasinglequery.
Letstakealookatthefollowingexampleinwhichallthestudentswiththeirrespectiveenrollmentsare
retrievedfromthedatabasebyusingeagerloading.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
//Loadallstudentsandrelatedenrollments
varstudents=context.Students
.Include(ss.Enrollments).ToList();

foreach(varstudentinstudents){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);

foreach(varenrollmentinstudent.Enrollments){
Console.WriteLine("EnrollmentID:{0},CourseID:{1}",
enrollment.EnrollmentID,enrollment.CourseID);
}
}
Console.ReadKey();
}
}
}

Whentheabovecodeiscompiledandexecutedyouwillreceivethefollowingoutput.
ID:1,Name:AliAlexander
EnrollmentID:1,CourseID:1050
EnrollmentID:2,CourseID:4022
EnrollmentID:3,CourseID:4041
ID:2,Name:MeredithAlonso
EnrollmentID:4,CourseID:1045
EnrollmentID:5,CourseID:3141
EnrollmentID:6,CourseID:2021
ID:3,Name:ArturoAnand
EnrollmentID:7,CourseID:1050
ID:4,Name:GytisBarzdukas
EnrollmentID:8,CourseID:1050
EnrollmentID:9,CourseID:4022

Belowaresomeoftheotherformsofeagerloadingquerieswhichcanbeused.
//LoadoneStudentanditsrelatedenrollments
varstudent1=context.Students
.Where(ss.FirstMidName=="Ali")
.Include(ss.Enrollments).FirstOrDefault();

http://www.tutorialspoint.com/cgibin/printpage.cgi

152/225

8/12/2016

EntityFrameworkQuickGuide

//LoadallStudentsandrelatedenrollments
//usingastringtospecifytherelationship
varstudentList=context.Students
.Include("Enrollments").ToList();
//LoadoneStudentanditsrelatedenrollments
//usingastringtospecifytherelationship
varstudent=context.Students
.Where(ss.FirstMidName=="Salman")
.Include("Enrollments").FirstOrDefault();

MultipleLevels
Itisalsopossibletoeagerlyloadmultiplelevelsofrelatedentities.Thefollowingqueriesshowexamplesof
Student,EnrollmentsandCourse.
//LoadallStudents,allrelatedenrollments,andallrelatedcourses
varstudentList=context.Students
.Include(ss.Enrollments.Select(cc.Course)).ToList();
//LoadallStudents,allrelatedenrollments,andallrelatedcourses
//usingastringtospecifytherelationships
varstudents=context.Students
.Include("Enrollments.Course").ToList();

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKLAZYLOADING
Lazyloadingistheprocesswherebyanentityorcollectionofentitiesisautomaticallyloadedfromthedatabase
thefirsttimethatapropertyreferringtotheentity/entitiesisaccessed.Lazyloadingmeansdelayingtheloading
ofrelateddata,untilyouspecificallyrequestforit.
WhenusingPOCOentitytypes,lazyloadingisachievedbycreatinginstancesofderivedproxytypesand
thenoverridingvirtualpropertiestoaddtheloadinghook.
Lazyloadingisprettymuchthedefault.
Ifyouleavethedefaultconfiguration,anddontexplicitlytellEntityFrameworkinyourquerythatyou
wantsomethingotherthanlazyloading,thenlazyloadingiswhatyouwillget.
Forexample,whenusingtheStudententityclass,therelatedEnrollmentswillbeloadedthefirsttimethe
Enrollmentsnavigationpropertyisaccessed.
Navigationpropertyshouldbedefinedaspublic,virtual.ContextwillNOTdolazyloadingiftheproperty
isnotdefinedasvirtual.
FollowingisaStudentclasswhichcontainsnavigationpropertyofEnrollments.
publicpartialclassStudent{
publicStudent(){
this.Enrollments=newHashSet<Enrollment>();
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

153/225

8/12/2016

EntityFrameworkQuickGuide

publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicSystem.DateTimeEnrollmentDate{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Letstakealookintoasimpleexampleinwhichstudentlistisloadedfromthedatabasefirstandthenitwillload
theenrollmentsofaparticularstudentwheneveryouneedit.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
//Loadingstudentsonly
IList<Student>students=context.Students.ToList<Student>();
foreach(varstudentinstudents){
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);

foreach(varenrollmentinstudent.Enrollments){
Console.WriteLine("EnrollmentID:{0},CourseID:{1}",
enrollment.EnrollmentID,enrollment.CourseID);
}
}
Console.ReadKey();
}
}
}

Whentheabovecodeiscompiledandexecuted,youwillreceivethefollowingoutput.
ID:1,Name:AliAlexander
EnrollmentID:1,CourseID:1050
EnrollmentID:2,CourseID:4022
EnrollmentID:3,CourseID:4041
ID:2,Name:MeredithAlonso
EnrollmentID:4,CourseID:1045
EnrollmentID:5,CourseID:3141
EnrollmentID:6,CourseID:2021
ID:3,Name:ArturoAnand
EnrollmentID:7,CourseID:1050
ID:4,Name:GytisBarzdukas
EnrollmentID:8,CourseID:1050
EnrollmentID:9,CourseID:4022
ID:5,Name:YanLi
EnrollmentID:10,CourseID:4041
ID:6,Name:PeggyJustice
EnrollmentID:11,CourseID:1045
ID:7,Name:LauraNorman
EnrollmentID:12,CourseID:3141

TurnOffLazyLoading

http://www.tutorialspoint.com/cgibin/printpage.cgi

154/225

8/12/2016

EntityFrameworkQuickGuide

Lazyloadingandserializationdontmixwell,andifyouarentcarefulyoucanendupqueryingforyourentire
databasejustbecauselazyloadingisenabled.Itsagoodpracticetoturnlazyloadingoffbeforeyouserializean
entity.

TurningOffforSpecificNavigationProperties
LazyloadingoftheEnrollmentscollectioncanbeturnedoffbymakingtheEnrollmentspropertynonvirtualas
showninthefollowingexample.
publicpartialclassStudent{
publicStudent(){
this.Enrollments=newHashSet<Enrollment>();
}

publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicSystem.DateTimeEnrollmentDate{get;set;}
publicICollection<Enrollment>Enrollments{get;set;}
}

TurnOffforAllEntities
LazyloadingcanbeturnedoffforallentitiesinthecontextbysettingaflagontheConfigurationpropertyto
falseasshowninthefollowingexample.
publicpartialclassUniContextEntities:DbContext{
publicUniContextEntities():base("name=UniContextEntities"){
this.Configuration.LazyLoadingEnabled=false;
}

protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
thrownewUnintentionalCodeFirstException();
}
}

Afterturningofflazyloading,nowwhenyouruntheaboveexampleagainyouwillseethattheEnrollmentsare
notloadedandonlystudentdataisretrieved.
ID:1,Name:AliAlexander
ID:2,Name:MeredithAlons
ID:3,Name:ArturoAnand
ID:4,Name:GytisBarzduka
ID:5,Name:YanLi
ID:6,Name:PeggyJustice
ID:7,Name:LauraNorman
ID:8,Name:NinoOlivetto

Werecommendyoutoexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKEXPLICITLOADING
Whenyoudisabledthelazyloading,itisstillpossibletolazilyloadrelatedentities,butitmustbedonewithan
explicitcall.
Unlikelazyloading,thereisnoambiguityorpossibilityofconfusionregardingwhenaqueryisrun.

http://www.tutorialspoint.com/cgibin/printpage.cgi

155/225

8/12/2016

EntityFrameworkQuickGuide

TodosoyouusetheLoadmethodontherelatedentitysentry.
Foraonetomanyrelationship,calltheLoadmethodonCollection.
Andforaonetoonerelationship,calltheLoadmethodonReference.
Letstakealookatthefollowingexampleinwhichlazyloadingisdisabledandthenthestudentwhosefirstname
isAliisretrieved.
Studentinformationisthenwrittenonconsole.Ifyoulookatthecode,enrollmentsinformationisalsowritten
butEnrollmentsentityisnotloadedyetsoforeachloopwillnotbeexecuted.
AfterthatEnrollmentsentityisloadedexplicitlynowstudentinformationandenrollmentsinformationwillbe
writtenontheconsolewindow.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
context.Configuration.LazyLoadingEnabled=false;
varstudent=(fromsincontext.Studentswheres.FirstMidName==
"Ali"selects).FirstOrDefault<Student>();
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
foreach(varenrollmentinstudent.Enrollments){
Console.WriteLine("EnrollmentID:{0},CourseID:{1}",
enrollment.EnrollmentID,enrollment.CourseID);
}
Console.WriteLine();
Console.WriteLine("ExplicitlyloadedEnrollments");
Console.WriteLine();
context.Entry(student).Collection(ss.Enrollments).Load();
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
foreach(varenrollmentinstudent.Enrollments){
Console.WriteLine("EnrollmentID:{0},CourseID:{1}",
enrollment.EnrollmentID,enrollment.CourseID);
}
Console.ReadKey();
}
}
}

Whentheaboveexampleisexecuted,youwillreceivethefollowingoutput.Firstonlystudentinformationis
displayedandafterexplicitlyloadingenrollmentsentity,bothstudentandhisrelatedenrollmentsinformation
isdisplayed.
ID:1,Name:AliAlexander
ExplicitlyloadedEnrollments
ID:1,Name:AliAlexander
EnrollmentID:1,CourseID:1050
EnrollmentID:2,CourseID:4022
EnrollmentID:3,CourseID:4041

http://www.tutorialspoint.com/cgibin/printpage.cgi

156/225

8/12/2016

EntityFrameworkQuickGuide

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKVALIDATION
InthischapterletuslearnaboutthevalidationtechniquesthatcanbeusedinADO.NETEntityFrameworkto
validatethemodeldata.EntityFrameworkprovidesagreatvarietyofvalidationfeaturesthatcanbe
implementedtoauserinterfaceforclientsidevalidationorcanbeusedforserversidevalidation.
InEntityFramework,datavalidationispartofthesolutionforcatchingbaddatainanapplication.
EntityFrameworkvalidatesalldatabeforeitiswrittentothedatabasebydefault,usingawiderangeof
datavalidationmethods.
However,EntityFrameworkcomesaftertheuserinterfacedatavalidation.Sointhatcasethereisaneed
forentityvalidationtohandleanyexceptionsthatEFthrowsandshowagenericmessage.
Therearesometechniquesofdatavalidationtoimproveyourerrorcheckingandhowtopasserror
messagesbacktotheuser.
DbContexthasanOverridablemethodcalledValidateEntity.WhenyoucallSaveChanges,EntityFramework
willcallthismethodforeachentityinitscachewhosestateisnotUnchanged.Youcanputvalidationlogic
directlyinhereasshowninthefollowingexamplefortheStudentEntity.
publicpartialclassUniContextEntities:DbContext{
protectedoverrideSystem.Data.Entity.Validation
.DbEntityValidationResultValidateEntity(DbEntityEntryentityEntry,
System.Collections.Generic.IDictionary<object,object>items){
if(entityEntry.EntityisStudent){
if(entityEntry.CurrentValues.GetValue<string>("FirstMidName")==""){
varlist=newList<System.Data.Entity
.Validation.DbValidationError>();
list.Add(newSystem.Data.Entity.Validation
.DbValidationError("FirstMidName","FirstMidNameisrequired"));
returnnewSystem.Data.Entity.Validation
.DbEntityValidationResult(entityEntry,list);
}
}
if(entityEntry.CurrentValues.GetValue<string>("LastName")==""){
varlist=newList<System.Data.Entity
.Validation.DbValidationError>();
list.Add(newSystem.Data.Entity.Validation
.DbValidationError("LastName","LastNameisrequired"));
returnnewSystem.Data.Entity.Validation
.DbEntityValidationResult(entityEntry,list);
}
returnbase.ValidateEntity(entityEntry,items);
}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

157/225

8/12/2016

EntityFrameworkQuickGuide

IntheaboveValidateEntitymethod,StudententityFirstMidNameandLastNamepropertiesarecheckedifany
ofthesepropertyhaveanemptystring,thenitwillreturnanerrormessage.
Letstakealookatasimpleexampleinwhichanewstudentiscreated,butthestudentsFirstMidNameisempty
stringasshowninthefollowingcode.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
Console.WriteLine("AddingnewStudenttothedatabase");
Console.WriteLine();
try{
context.Students.Add(newStudent(){
FirstMidName="",
LastName="Upston"
});
context.SaveChanges();
}catch(DbEntityValidationExceptiondbValidationEx){
foreach(DbEntityValidationResultentityErrin
dbValidationEx.EntityValidationErrors){
foreach(DbValidationErrorerrorinentityErr.ValidationErrors){
Console.WriteLine("Error:{0}",error.ErrorMessage);
}
}
}
Console.ReadKey();
}
}
}

Whentheaboveexampleiscompiledandexecuted,youwillreceivethefollowingerrormessageontheconsole
window.
AddingnewStudenttothedatabase
Error:FirstMidNameisrequired

Werecommendyoutoexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKTRACKCHANGES
EntityFrameworkprovidesabilitytotrackthechangesmadetoentitiesandtheirrelations,sothecorrect
updatesaremadeonthedatabasewhentheSaveChangesmethodofcontextiscalled.Thisisakeyfeatureofthe
EntityFramework.
TheChangeTrackingtrackschangeswhileaddingnewrecordstotheentitycollection,modifyingor
removingexistingentities.
ThenallthechangesarekeptbytheDbContextlevel.
ThesetrackchangesarelostiftheyarenotsavedbeforetheDbContextobjectisdestroyed.

http://www.tutorialspoint.com/cgibin/printpage.cgi

158/225

8/12/2016

EntityFrameworkQuickGuide

DbChangeTrackerclassgivesyoualltheinformationaboutcurrententitiesbeingtrackedbythecontext.
Totrackanyentitybythecontext,itmusthavetheprimarykeyproperty.
InEntityFramework,changetrackingisenabledbydefault.Youcanalsodisablechangetrackingbysettingthe
AutoDetectChangesEnabledpropertyofDbContexttofalse.IfthispropertyissettotruethentheEntity
Frameworkmaintainsthestateofentities.
using(varcontext=newUniContextEntities()){
context.Configuration.AutoDetectChangesEnabled=true;
}

Letstakealookatthefollowingexampleinwhichthestudentsandtheirenrollmentsareretrievedfromthe
database.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
context.Configuration.AutoDetectChangesEnabled=true;
Console.WriteLine("RetrieveStudent");
varstudent=(fromsincontext.Studentswheres.FirstMidName==
"Ali"selects).FirstOrDefault<Student>();
stringname=student.FirstMidName+""+student.LastName;
Console.WriteLine("ID:{0},Name:{1}",student.ID,name);
Console.WriteLine();
Console.WriteLine("Retrieveallrelatedenrollments");
foreach(varenrollmentinstudent.Enrollments){
Console.WriteLine("EnrollmentID:{0},CourseID:{1}",
enrollment.EnrollmentID,enrollment.CourseID);
}
Console.WriteLine();
Console.WriteLine("Contexttrackingchangesof{0}entity.",
context.ChangeTracker.Entries().Count());
varentries=context.ChangeTracker.Entries();
foreach(varentryinentries){
Console.WriteLine("EntityName:{0}",entry.Entity.GetType().Name);
Console.WriteLine("Status:{0}",entry.State);
}
Console.ReadKey();
}
}
}

Whentheaboveexampleiscompiledandexecutedyouwillreceivethefollowingoutput.
RetrieveStudent
ID:1,Name:AliAlexander
Retrieveallrelatedenrollments
EnrollmentID:1,CourseID:1050

http://www.tutorialspoint.com/cgibin/printpage.cgi

159/225

8/12/2016

EntityFrameworkQuickGuide

EnrollmentID:2,CourseID:4022
EnrollmentID:3,CourseID:4041
Contexttrackingchangesof4entity.
EntityName:Student
Status:Unchanged
EntityName:Enrollment
Status:Unchanged
EntityName:Enrollment
Status:Unchanged
EntityName:Enrollment
Status:Unchanged

Youcanseethatalldataisonlyretrievedfromthedatabasethatswhythestatusisunchangedforallthe
entities.
Letusnowtakealookatanothersimpleexampleinwhichwewilladdonemoreenrollmentanddeleteone
studentfromthedatabase.Followingisthecodeinwhichnewenrollmentisaddedandonestudentisdeleted.
classProgram{
staticvoidMain(string[]args){
using(varcontext=newUniContextEntities()){
context.Configuration.AutoDetectChangesEnabled=true;
Enrollmentenr=newEnrollment(){
StudentID=1,CourseID=3141
};
Console.WriteLine("AddingNewEnrollment");
context.Enrollments.Add(enr);
Console.WriteLine("DeleteStudent");
varstudent=(fromsincontext.Studentswheres.ID==
23selects).SingleOrDefault<Student>();
context.Students.Remove(student);
Console.WriteLine("");
Console.WriteLine("Contexttrackingchangesof{0}entity.",
context.ChangeTracker.Entries().Count());
varentries=context.ChangeTracker.Entries();
foreach(varentryinentries){
Console.WriteLine("EntityName:{0}",entry.Entity.GetType().Name);
Console.WriteLine("Status:{0}",entry.State);
}
Console.ReadKey();
}
}
}

Whentheaboveexampleiscompiledandexecuted,youwillreceivethefollowingoutput.
AddingNewEnrollment
DeleteStudent
Contexttrackingchangesof2entity.
EntityName:Enrollment
Status:Added

http://www.tutorialspoint.com/cgibin/printpage.cgi

160/225

8/12/2016

EntityFrameworkQuickGuide

EntityName:Student
Status:Deleted

Youcannowseethatthestatusofenrollmententityissettoadded,andthestatusofstudententityisdeleted,
becausenewenrollmenthasbeenaddedandonestudentisremovedfromthedatabase.
Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKCOLOREDENTITIES
InEntityFramework,ColoredEntityismainlyallaboutchangingthecolorofentityinthedesignersothatitis
easyfordeveloperstoidentifyrelatedgroupsofentitiesintheVisualStudiodesigner.Thisfeaturewasfirst
introducedinEntityFramework5.0.
Thisfeaturehasnothingtodowithperformanceaspects.
Whenyouhavealargescaleprojectandmanyentitiesinoneedmxfile,thenthisfeatureisveryhelpfulto
separateyourentitiesindifferentmodules.
Ifyouareworkingwithedmxfileandyouhaveopeneditindesigner,tochangethecolor,selectanentityonthe
designwindows.ThenrightclickandselectProperties.

http://www.tutorialspoint.com/cgibin/printpage.cgi

161/225

8/12/2016

EntityFrameworkQuickGuide

InthePropertieswindow,selecttheFillColorproperty.

http://www.tutorialspoint.com/cgibin/printpage.cgi

162/225

8/12/2016

EntityFrameworkQuickGuide

Specifythecolorusingeitheravalidcolorname,forexample,GreenoravalidRGB255, 128, 128 oryoucanalso


selectfromthecolorpicker.

http://www.tutorialspoint.com/cgibin/printpage.cgi

163/225

8/12/2016

EntityFrameworkQuickGuide

Tochangethecolorofmultipleentitiesinonego,selectmultipleentitiesandchangeFillColorforallofthem
usingthepropertywindow.

http://www.tutorialspoint.com/cgibin/printpage.cgi

164/225

8/12/2016

EntityFrameworkQuickGuide

Youcanalsochangetheformatofpropertiesbyselectinganyofthefollowingoptions
DisplayName
DisplayNameandType
Bydefault,displaynameoptionisselected.Tochangethepropertyformat,rightclickonthedesignerwindow.

http://www.tutorialspoint.com/cgibin/printpage.cgi

165/225

8/12/2016

EntityFrameworkQuickGuide

SelectScalarPropertyFormatDisplayNameandType.

http://www.tutorialspoint.com/cgibin/printpage.cgi

166/225

8/12/2016

EntityFrameworkQuickGuide

Youcannowseethatthetypeisalsodisplayedalongwiththename.

ENTITYFRAMEWORKCODEFIRSTAPPROACH
TheEntityFrameworkprovidesthreeapproachestocreateanentitymodelandeachonehastheirownprosand
cons.
CodeFirst
DatabaseFirst
ModelFirst
Inthischapter,wewillbrieflydescribethecodefirstapproach.Somedevelopersprefertoworkwiththe
DesignerinCodewhileotherswouldratherjustworkwiththeircode.Forthosedevelopers,EntityFramework
hasamodelingworkflowreferredtoasCodeFirst.
CodeFirstmodelingworkflowtargetsadatabasethatdoesntexistandCodeFirstwillcreateit.
ItcanalsobeusedifyouhaveanemptydatabaseandthenCodeFirstwilladdnewtablestoit.
CodeFirstallowsyoutodefineyourmodelusingC#orVB.Netclasses.
Additionalconfigurationcanoptionallybeperformedusingattributesonyourclassesandpropertiesor
byusingafluentAPI.

http://www.tutorialspoint.com/cgibin/printpage.cgi

167/225

8/12/2016

EntityFrameworkQuickGuide

WhyCodeFirst?
CodeFirstisreallymadeupofasetofpuzzlepieces.Firstareyourdomainclasses.
ThedomainclasseshavenothingtodowithEntityFramework.They'rejusttheitemsofyourbusiness
domain.
EntityFramework,then,hasacontextthatmanagestheinteractionbetweenthoseclassesandyour
database.
ThecontextisnotspecifictoCodeFirst.It'sanEntityFrameworkfeature.
CodeFirstaddsamodelbuilderthatinspectsyourclassesthatthecontextismanaging,andthenusesa
setofrulesorconventionstodeterminehowthoseclassesandtherelationshipsdescribeamodel,and
howthatmodelshouldmaptoyourdatabase.
Allofthishappensatruntime.You'llneverseethismodel,it'sjustinmemory.
CodeFirstalsohastheabilitytousethatmodeltocreateadatabaseifyouwantedto.
Itcanalsoupdatethedatabaseifthemodelchanges,usingafeaturecalledCodeFirstMigrations.

EnvironmentSetup

http://www.tutorialspoint.com/cgibin/printpage.cgi

168/225

8/12/2016

EntityFrameworkQuickGuide

TostartworkingwithEFCodeFirstapproachyouneedthefollowingtoolstobeinstalledonyoursystem.
VisualStudio2013. netf ramework4.5.2 orlaterversion.
MSSQLServer2012orlatter.
EntityFrameworkviaNuGetPackage.

InstallEFviaNuGetPackage
Step1First,createtheconsoleapplicationfromFileNewProject
Step2SelectWindowsfromtheleftpaneandConsoleApplicationfromthetemplatepane.

Step3EnterEFCodeFirstDemoasthenameandselectOK.
Step4RightclickonyourprojectinthesolutionexplorerandselectManageNuGetPackages

http://www.tutorialspoint.com/cgibin/printpage.cgi

169/225

8/12/2016

EntityFrameworkQuickGuide

ThiswillopenNuGetPackageManager,andsearchforEntityFramework.Thiswillsearchforallthepackages
relatedtoEntityFramework.
Step5SelectEntityFrameworkandclickonInstall.OrfromtheToolsmenuclickNuGetPackageManager
andthenclickPackageManagerConsole.InthePackageManagerConsolewindow,enterthefollowing
command:InstallPackageEntityFramework.

http://www.tutorialspoint.com/cgibin/printpage.cgi

170/225

8/12/2016

EntityFrameworkQuickGuide

Whentheinstallationiscomplete,youwillseethefollowingmessageintheoutputwindowSuccessfully
installed'EntityFramework6.1.2'toEFCodeFirstDemo.
Afterinstallation,EntityFramework.dllwillbeincludedinyourproject,asshowninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

171/225

8/12/2016

EntityFrameworkQuickGuide

NowyouarereadytostartworkingonCodeFirstapproach.

ENTITYFRAMEWORKFIRSTEXAMPLE
Letsdefineaverysimplemodelusingclasses.WerejustdefiningthemintheProgram.csfilebutinarealworld
applicationyouwillsplityourclassesintoseparatefilesandpotentiallyaseparateproject.Followingisadata
modelwhichwewillbecreatingusingCodeFirstapproach.

CreateModel

http://www.tutorialspoint.com/cgibin/printpage.cgi

172/225

8/12/2016

EntityFrameworkQuickGuide

AddthefollowingthreeclassesinProgram.csfileusingthefollowingcodeforStudentclass.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

TheIDpropertywillbecometheprimarykeycolumnofthedatabasetablethatcorrespondstothisclass.
TheEnrollmentspropertyisanavigationproperty.Navigationpropertiesholdotherentitiesthatare
relatedtothisentity.
Inthiscase,theEnrollmentspropertyofaStudententitywillholdalloftheEnrollmententitiesthatare
relatedtothatStudententity.
NavigationpropertiesaretypicallydefinedasvirtualsothattheycantakeadvantageofcertainEntity
Frameworkfunctionalitysuchaslazyloading.
Ifanavigationpropertycanholdmultipleentitiesasinmany to manyorone tomanyrelationships ,
itstypemustbealistinwhichentriescanbeadded,deleted,andupdated,suchasICollection.
FollowingistheimplementationforCourseclass.
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
publicintCredits{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

TheEnrollmentspropertyisanavigationproperty.ACourseentitycanberelatedtoanynumberofEnrollment
entities.
FollowingistheimplementationforEnrollmentclassandenum.
publicenumGrade{
A,B,C,D,F
}
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicGrade?Grade{get;set;}

publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}

TheEnrollmentIDpropertywillbetheprimarykey.
TheGradepropertyisanenum.ThequestionmarkaftertheGradetypedeclarationindicatesthatthe
Gradepropertyisnullable.

http://www.tutorialspoint.com/cgibin/printpage.cgi

173/225

8/12/2016

EntityFrameworkQuickGuide

Agradethat'snullisdifferentfromazerograde.Nullmeansagradeisn'tknownorhasn'tbeenassigned
yet.
TheStudentIDandCourseIDpropertiesareforeignkeys,andthecorrespondingnavigationproperties
areStudentandCourse.
AnEnrollmententityisassociatedwithoneStudentandoneCourseentity,sothepropertycanonlyhold
asingleStudentandCourseentity.

CreateDatabaseContext
ThemainclassthatcoordinatesEntityFrameworkfunctionalityforagivendatamodelisthedatabasecontext
classwhichallowstoqueryandsavedata.YoucancreatethisclassbyderivingfromtheDbContextclassand
exposingatypedDbSetforeachclassinourmodel.FollowingistheimplementationonMyContextclass,which
isderivedfromDbContextclass.
publicclassMyContext:DbContext{
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

FollowingisthecompletecodeinProgram.csfile.
usingSystem.ComponentModel.DataAnnotations.Schema;
usingSystem.Data.Entity;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceEFCodeFirstDemo{
classProgram{
staticvoidMain(string[]args){}
}
publicenumGrade{
A,B,C,D,F
}
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicGrade?Grade{get;set;}

publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassCourse{

http://www.tutorialspoint.com/cgibin/printpage.cgi

174/225

8/12/2016

EntityFrameworkQuickGuide

publicintCourseID{get;set;}
publicstringTitle{get;set;}
publicintCredits{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassMyContext:DbContext{
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}
}

Theabovecodeisallweneedtostartstoringandretrievingdata.Letsaddsomedataandthenretrieveit.
Followingisthecodeinmainmethod.
staticvoidMain(string[]args){
using(varcontext=newMyContext()){
//CreateandsaveanewStudents
Console.WriteLine("Addingnewstudents");
varstudent=newStudent{
FirstMidName="Alain",LastName="Bomer",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
};
context.Students.Add(student);

varstudent1=newStudent{
FirstMidName="Mark",LastName="Upston",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
};
context.Students.Add(student1);
context.SaveChanges();
//DisplayallStudentsfromthedatabase
varstudents=(fromsincontext.Students
orderbys.FirstMidNameselects).ToList<Student>();
Console.WriteLine("RetrieveallStudentsfromthedatabase:");
foreach(varstdntinstudents){
stringname=stdnt.FirstMidName+""+stdnt.LastName;
Console.WriteLine("ID:{0},Name:{1}",stdnt.ID,name);
}

Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}
}

Whentheabovecodeisexecuted,youwillreceivethefollowingoutput.
Addingnewstudents
RetrieveallStudentsfromthedatabase:
ID:1,Name:AlainBomer

http://www.tutorialspoint.com/cgibin/printpage.cgi

175/225

8/12/2016

EntityFrameworkQuickGuide

ID:2,Name:MarkUpston
Pressanykeytoexit...

Nowthequestionthatcomestomindis,whereisthedataandthedatabaseinwhichwehaveaddedsomedata
andthenretrieveditfromdatabase.Byconvention,DbContexthascreatedadatabaseforyou.
IfalocalSQLExpressinstanceisavailablethenCodeFirsthascreatedthedatabaseonthatinstance.
IfSQLExpressisntavailable,thenCodeFirstwilltryanduseLocalDb.
Thedatabaseisnamedafterthefullyqualifiednameofthederivedcontext.
Inourcase,SQLExpressinstanceisavailable,andthedatabasenameisEFCodeFirstDemo.MyContextasshown
inthefollowingimage.

ThesearejustthedefaultconventionsandtherearevariouswaystochangethedatabasethatCodeFirst
uses.
Asyoucanseeintheaboveimage,ithascreatedStudents,CoursesandEnrollmentstablesandeachtable
containscolumnswithappropriatedatatypeandlength.
Thecolumnnamesanddatatypealsomatcheswiththepropertiesoftherespectivedomainclasses.

DatabaseInitialization
Intheaboveexample,wehaveseenthatCodeFirstcreatesadatabaseautomatically,butifyouwanttochange
thenameofthedatabaseandserver,letusseehowCodeFirstdecidesthedatabasenameandserverwhile
initializingadatabase.Takealookatthefollowingdiagram.

http://www.tutorialspoint.com/cgibin/printpage.cgi

176/225

8/12/2016

EntityFrameworkQuickGuide

Youcandefinethebaseconstructorofthecontextclassinthefollowingways.
NoParameter
DatabaseName
ConnectionStringName

NoParameter
Ifyouspecifythebaseconstructorofthecontextclasswithoutanyparameterasshownintheaboveexample,
thenentityframeworkwillcreateadatabaseinyourlocalSQLEXPRESSserverwithaname{Namespace}.
{Contextclassname}.
Intheaboveexample,thedatabasewhichiscreatedautomaticallyhasthenameEFCodeFirstDemo.MyContext.
Ifyoulookatthename,youwillfindthatEFCodeFirstDemoisthenamespaceandMyContextisthecontext
classnameasshowninthefollowingcode.

http://www.tutorialspoint.com/cgibin/printpage.cgi

177/225

8/12/2016

EntityFrameworkQuickGuide

publicclassMyContext:DbContext{
publicMyContext():base(){}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

DatabaseName
Ifyoupassthedatabasenameasaparameterinabaseconstructorofthecontextclass,thenCodeFirstwill
createadatabaseautomaticallyagain,butthistimethenamewillbetheonepassedasparameterinthebase
constructoronthelocalSQLEXPRESSdatabaseserver.
Inthefollowingcode,MyContextDBisspecifiedasparameterinthebaseconstructor.Ifrunyourapplication,
thenthedatabasewithMyContextDBnamewillbecreatedinyourlocalSQLserver.
publicclassMyContext:DbContext{
publicMyContext():base("MyContextDB"){}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

ConnectionStringName
ThisisaneasywaytotellDbContexttouseadatabaseserverotherthanSQLExpressorLocalDb.Youmay
choosetoputaconnectionstringinyourapp.configfile.
Ifthenameoftheconnectionstringmatchesthenameofyourcontext
eitherwithorwithoutnamespacequalif ication ,thenitwillbefoundbyDbContextwhentheparameter
lessconstructorisused.
Iftheconnectionstringnameisdifferentfromthenameofyourcontext,thenyoucantellDbContextto
usethisconnectioninCodeFirstmodebypassingtheconnectionstringnametotheDbContext
constructor.
publicclassMyContext:DbContext{
publicMyContext():base("name=MyContextDB"){}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

Intheabovecode,snippetofcontextclassconnectionstringisspecifiedasaparameterinthebase
constructor.
Connectionstringnamemuststartwith"name="otherwise,itwillconsideritasadatabasename.
Thisformmakesitexplicitthatyouexpecttheconnectionstringtobefoundinyourconfigfile.An
exceptionwillbethrownifaconnectionstringwiththegivennameisnotfound.
<connectionStrings>
<addname="MyContextDB"
connectionString="DataSource=.;InitialCatalog=EFMyContextDB;IntegratedSecurity=
true"
providerName="System.Data.SqlClient"/>
</connectionStrings>

http://www.tutorialspoint.com/cgibin/printpage.cgi

178/225

8/12/2016

EntityFrameworkQuickGuide

Thedatabasenameintheconnectionstringinapp.configisEFMyContextDB.CodeFirstwillcreatea
newEFMyContextDBdatabaseoruseexistingEFMyContextDBdatabaseatlocalSQLServer.

DomainClasses
SofarwevejustletEFdiscoverthemodelusingitsdefaultconventions,buttherearegoingtobetimeswhen
ourclassesdontfollowtheconventionsandweneedtobeabletoperformfurtherconfiguration.Butyoucan
overridetheseconventionsbyconfiguringyourdomainclassestoprovideEFwiththeinformationitneeds.
Therearetwooptionstoconfigureyourdomainclasses
DataAnnotations
FluentAPI

DataAnnotations
DataAnnotationsisusedtoconfigureyourclasseswhichwillhighlightthemostcommonlyneeded
configurations.DataAnnotationsarealsounderstoodbyanumberof.NETapplications,suchasASP.NETMVC
whichallowtheseapplicationstoleveragethesameannotationsforclientsidevalidations.
Followingarethedataannotationsusedinstudentclass.
publicclassEnrollment{
[Key]
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicGrade?Grade{get;set;}
[ForeignKey("CourseID")]
publicvirtualCourseCourse{get;set;}
[ForeignKey("ID")]
publicvirtualStudentStudent{get;set;}
}

FluentAPI
Mostmodelconfigurationcanbedoneusingsimpledataannotations.ThefluentAPIisaadvancedwayof
specifyingmodelconfigurationthatcoverseverythingthatdataannotationscando,inadditiontosomemore
advancedconfigurationnotpossiblewithdataannotations.DataannotationsandthefluentAPIcanbeused
together.
ToaccessthefluentAPIyouoverridetheOnModelCreatingmethodinDbContext.Nowletsrenamethecolumn
nameinstudenttablefromFirstMidNametoFirstNameasshowninthefollowingcode.
publicclassMyContext:DbContext{
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
modelBuilder.Entity<Student>().Property(ss.FirstMidName)
.HasColumnName("FirstName");
}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

ENTITYFRAMEWORKDATAANNOTATIONS
http://www.tutorialspoint.com/cgibin/printpage.cgi

179/225

8/12/2016

EntityFrameworkQuickGuide

ENTITYFRAMEWORKDATAANNOTATIONS
DataAnnotationsisusedtoconfiguretheclasseswhichwillhighlightthemostcommonlyneededconfigurations.
DataAnnotationsarealsounderstoodbyanumberof.NETapplications,suchasASP.NETMVCwhichallows
theseapplicationstoleveragethesameannotationsforclientsidevalidations.DataAnnotationattributes
overridedefaultCodeFirstconventions.
System.ComponentModel.DataAnnotationsincludesthefollowingattributesthatimpactsthenullability
orsizeofthecolumn.
Key
Timestamp
ConcurrencyCheck
Required
MinLength
MaxLength
StringLength
System.ComponentModel.DataAnnotations.Schemanamespaceincludesthefollowingattributesthat
impactstheschemaofthedatabase.
Table
Column
Index
ForeignKey
NotMapped
InverseProperty

Key
EntityFrameworkreliesoneveryentityhavingakeyvaluethatitusesfortrackingentities.Oneofthe
conventionsthatCodeFirstdependsonishowitimplieswhichpropertyisthekeyineachoftheCodeFirst
classes.
ConventionistolookforapropertynamedIdoronethatcombinestheclassnameandId,suchas
StudentId.
Thepropertywillmaptoaprimarykeycolumninthedatabase.
TheStudent,CourseandEnrollmentclassesfollowthisconvention.
NowletssupposeStudentclassusedthenameStdntIDinsteadofID.WhenCodeFirstdoesnotfindaproperty
thatmatchesthisconvention,itwillthrowanexceptionbecauseofEntityFrameworksrequirementthatyou
musthaveakeyproperty.Youcanusethekeyannotationtospecifywhichpropertyistobeusedasthe
EntityKey.
LetstakealookatthefollowingcodeofaStudentclasswhichcontainsStdntID,butitdoesntfollowthedefault
CodeFirstconvention.Sotohandlethis,aKeyattributeisaddedwhichwillmakeitaprimarykey.
publicclassStudent{

http://www.tutorialspoint.com/cgibin/printpage.cgi

180/225

8/12/2016

EntityFrameworkQuickGuide

[Key]
publicintStdntID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

WhenyourunyourapplicationandlookintoyourdatabaseinSQLServerExploreryouwillseethatthe
primarykeyisnowStdntIDinStudentstable.

EntityFrameworkalsosupportscompositekeys.Compositekeysarealsoprimarykeysthatconsistofmore
thanoneproperty.Forexample,youhaveaDrivingLicenseclasswhoseprimarykeyisacombinationof
LicenseNumberandIssuingCountry.
publicclassDrivingLicense{
[Key,Column(Order=1)]
publicintLicenseNumber{get;set;}
[Key,Column(Order=2)]
publicstringIssuingCountry{get;set;}
publicDateTimeIssued{get;set;}
publicDateTimeExpires{get;set;}
}

Whenyouhavecompositekeys,EntityFrameworkrequiresyoutodefineanorderofthekeyproperties.You
candothisusingtheColumnannotationtospecifyanorder.

http://www.tutorialspoint.com/cgibin/printpage.cgi

181/225

8/12/2016

EntityFrameworkQuickGuide

Timestamp
CodeFirstwilltreatTimestamppropertiesthesameasConcurrencyCheckproperties,butitwillalsoensure
thatthedatabasefieldthatcodefirstgeneratesisnonnullable.
It'smorecommontouserowversionortimestampfieldsforconcurrencychecking.
RatherthanusingtheConcurrencyCheckannotation,youcanusethemorespecificTimeStamp
annotationaslongasthetypeofthepropertyisbytearray.
Youcanonlyhaveonetimestamppropertyinagivenclass.
LetstakealookatasimpleexamplebyaddingtheTimeStamppropertytotheCourseclass
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
publicintCredits{get;set;}
[Timestamp]
publicbyte[]TStamp{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Asyoucanseeintheaboveexample,TimestampattributeisappliedtoByte[]propertyoftheCourseclass.So,
CodeFirstwillcreateatimestampcolumnTStampintheCoursestable.

ConcurrencyCheck

http://www.tutorialspoint.com/cgibin/printpage.cgi

182/225

8/12/2016

EntityFrameworkQuickGuide

TheConcurrencyCheckannotationallowsyoutoflagoneormorepropertiestobeusedforconcurrency
checkinginthedatabasewhenausereditsordeletesanentity.Ifyou'vebeenworkingwiththeEFDesigner,this
alignswithsettingaproperty'sConcurrencyModetoFixed.
LetstakealookatasimpleexampleofhowConcurrencyCheckworksbyaddingittotheTitlepropertyin
Courseclass.
publicclassCourse{
publicintCourseID{get;set;}
[ConcurrencyCheck]
publicstringTitle{get;set;}
publicintCredits{get;set;}
[Timestamp,DataType("timestamp")]
publicbyte[]TimeStamp{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

IntheaboveCourseclass,ConcurrencyCheckattributeisappliedtotheexistingTitleproperty.Now,CodeFirst
willincludeTitlecolumninupdatecommandtocheckforoptimisticconcurrencyasshowninthefollowingcode.
execsp_executesqlN'UPDATE[dbo].[Courses]
SET[Title]=@0
WHERE(([CourseID]=@1)AND([Title]=@2))
',N'@0nvarchar(max),@1int,@2nvarchar(max)',@0=N'Maths',@1=1,@2=N'Calculus'
go

RequiredAnnotation
TheRequiredannotationtellsEFthataparticularpropertyisrequired.Letstakealookatthefollowing
StudentclassinwhichRequiredidisaddedtotheFirstMidNameproperty.RequiredattributewillforceEFto
ensurethatthepropertyhasdatainit.
publicclassStudent{
[Key]
publicintStdntID{get;set;}
[Required]
publicstringLastName{get;set;}
[Required]
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Asseenintheaboveexample,RequiredattributeisappliedtoFirstMidNameandLastName.So,CodeFirstwill
createaNOTNULLFirstMidNameandLastNamecolumnsintheStudentstableasshowninthefollowing
image.

http://www.tutorialspoint.com/cgibin/printpage.cgi

183/225

8/12/2016

EntityFrameworkQuickGuide

MaxLength
TheMaxLengthattributeallowsyoutospecifyadditionalpropertyvalidations.Itcanbeappliedtoastringor
arraytypepropertyofadomainclass.EFCodeFirstwillsetthesizeofacolumnasspecifiedinMaxLength
attribute.
LetstakealookatthefollowingCourseclassinwhichMaxLength24attributeisappliedtoTitleproperty.
publicclassCourse{
publicintCourseID{get;set;}
[ConcurrencyCheck]
[MaxLength(24)]
publicstringTitle{get;set;}
publicintCredits{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Whenyouruntheaboveapplication,CodeFirstwillcreateanvarchar24columnTitleintheCourseIdtableas
showninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

184/225

8/12/2016

EntityFrameworkQuickGuide

WhentheusersetstheTitlewhichcontainsmorethan24characters,thenEFwillthrowEntityValidationError.

MinLength
TheMinLengthattributealsoallowsyoutospecifyadditionalpropertyvalidations,justasyoudidwith
MaxLength.MinLengthattributecanalsobeusedwithMaxLengthattributeasshowninthefollowingcode.
publicclassCourse{
publicintCourseID{get;set;}
[ConcurrencyCheck]
[MaxLength(24),MinLength(5)]
publicstringTitle{get;set;}
publicintCredits{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

EFwillthrowEntityValidationError,ifyousetavalueofTitlepropertylessthanthespecifiedlengthin
MinLengthattributeorgreaterthanspecifiedlengthinMaxLengthattribute.

StringLength
StringLengthalsoallowsyoutospecifyadditionalpropertyvalidationslikeMaxLength.Theonlydifferenceis
thatStringLengthattributecanonlybeappliedtoastringtypepropertyofDomainclasses.
publicclassCourse{
publicintCourseID{get;set;}
[StringLength(24)]
publicstringTitle{get;set;}

http://www.tutorialspoint.com/cgibin/printpage.cgi

185/225

8/12/2016

EntityFrameworkQuickGuide

publicintCredits{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

EntityFrameworkalsovalidatesthevalueofapropertyforStringLengthattribute.IftheusersetstheTitle
whichcontainsmorethan24characters,thenEFwillthrowEntityValidationError.

Table
DefaultCodeFirstconventioncreatesatablenamesimilartotheclassname.IfyouarelettingCodeFirstcreate
thedatabase,andalsowanttochangethenameofthetablesitiscreating.Then
YoucanuseCodeFirstwithanexistingdatabase.Butit'snotalwaysthecasethatthenamesoftheclasses
matchthenamesofthetablesinyourdatabase.
Tableattributeoverridesthisdefaultconvention.
EFCodeFirstwillcreateatablewithaspecifiednameinTableattributeforagivendomainclass.
LetstakealookatthefollowingexampleinwhichtheclassisnamedStudentandbyconvention,CodeFirst
presumesthiswillmaptoatablenamedStudents.Ifthat'snotthecase,youcanspecifythenameofthetable
withtheTableattributeasshowninthefollowingcode.
[Table("StudentsInfo")]
publicclassStudent{
[Key]
publicintStdntID{get;set;}
[Required]
publicstringLastName{get;set;}
[Required]
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

NowyoucanseethatTableattributespecifiesthetableasStudentsInfo.Whenthetableisgenerated,youwill
seethetablenameStudentsInfoasshowninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

186/225

8/12/2016

EntityFrameworkQuickGuide

YoucannotonlyspecifythetablenamebutyoucanalsospecifyaschemaforthetableusingTableattributeas
showninthefollowingcode.
[Table("StudentsInfo",Schema="Admin")]
publicclassStudent{
[Key]
publicintStdntID{get;set;}
[Required]
publicstringLastName{get;set;}
[Required]
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Youcanseeintheaboveexample,thetableisspecifiedwithadminschema.NowCodeFirstwillcreate
StudentsInfotableinAdminschemaasshowninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

187/225

8/12/2016

EntityFrameworkQuickGuide

Column
ItisalsothesameasTableattribute,butTableattributeoverridesthetablebehaviorwhileColumnattribute
overridesthecolumnbehavior.DefaultCodeFirstconventioncreatesacolumnnamesimilartotheproperty
name.IfyouarelettingCodeFirstcreatethedatabase,andalsowanttochangethenameofthecolumnsinyour
tables.Then
Columnattributeoverridesthedefaultconvention.
EFCodeFirstwillcreateacolumnwithaspecifiednameintheColumnattributeforagivenproperty.
LetstakealookatthefollowingexampleinwhichthepropertyisnamedFirstMidNameandbyconvention,
CodeFirstpresumesthiswillmaptoacolumnnamedFirstMidName.
Ifthat'snotthecaseyoucanspecifythenameofthecolumnwiththeColumnattributeasshowninthefollowing
code.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
[Column("FirstName")]
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

YoucanseethatColumnattributespecifiesthecolumnasFirstName.Whenthetableisgenerated,youwillsee
thecolumnnameFirstNameasshowninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

188/225

8/12/2016

EntityFrameworkQuickGuide

Index
TheIndexattributewasintroducedinEntityFramework6.1.Ifyouareusinganearlierversion,theinformation
inthissectiondoesnotapply.
YoucancreateanindexononeormorecolumnsusingtheIndexAttribute.
AddingtheattributetooneormorepropertieswillcauseEFtocreatethecorrespondingindexinthe
databasewhenitcreatesthedatabase.
Indexesmaketheretrievalofdatafasterandefficient,inmostcases.However,overloadingatableor
viewwithindexescouldunpleasantlyaffecttheperformanceofotheroperationssuchasinsertsor
updates.
IndexingisthenewfeatureinEntityFrameworkwhereyoucanimprovetheperformanceofyourCode
Firstapplicationbyreducingthetimerequiredtoquerydatafromthedatabase.
YoucanaddindexestoyourdatabaseusingtheIndexattribute,andoverridethedefaultUniqueand
Clusteredsettingstogettheindexbestsuitedtoyourscenario.
Bydefault,theindexwillbenamedIX_<propertyname>
LetstakealookatthefollowingcodeinwhichIndexattributeisaddedinCourseclassforCredits.
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
[Index]
publicintCredits{get;set;}

http://www.tutorialspoint.com/cgibin/printpage.cgi

189/225

8/12/2016

EntityFrameworkQuickGuide

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

YoucanseethattheIndexattributeisappliedtotheCreditsproperty.Whenthetableisgenerated,youwillsee
IX_CreditsinIndexes.

Bydefault,indexesarenonunique,butyoucanusetheIsUniquenamedparametertospecifythatanindex
shouldbeunique.Thefollowingexampleintroducesauniqueindexasshowninthefollowingcode.
publicclassCourse{
publicintCourseID{get;set;}
[Index(IsUnique=true)]

publicstringTitle{get;set;}
[Index]

publicintCredits{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

ForeignKey
CodeFirstconventionwilltakecareofthemostcommonrelationshipsinyourmodel,buttherearesomecases
whereitneedshelp.Forexample,bychangingthenameofthekeypropertyintheStudentclasscreateda
problemwithitsrelationshiptoEnrollmentclass.
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicGrade?Grade{get;set;}

http://www.tutorialspoint.com/cgibin/printpage.cgi

190/225

8/12/2016

EntityFrameworkQuickGuide

publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}
publicclassStudent{
[Key]
publicintStdntID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Whilegeneratingthedatabase,CodeFirstseestheStudentIDpropertyintheEnrollmentclassandrecognizesit,
bytheconventionthatitmatchesaclassnameplusID,asaforeignkeytotheStudentclass.However,thereis
noStudentIDpropertyintheStudentclass,butitisStdntIDpropertyisStudentclass.
ThesolutionforthisistocreateanavigationpropertyintheEnrollmentandusetheForeignKey
DataAnnotationtohelpCodeFirstunderstandhowtobuildtherelationshipbetweenthetwoclassesasshown
inthefollowingcode.
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}

publicGrade?Grade{get;set;}
publicvirtualCourseCourse{get;set;}
[ForeignKey("StudentID")]

publicvirtualStudentStudent{get;set;}
}

YoucanseenowthattheForeignKeyattributeisappliedtothenavigationproperty.

http://www.tutorialspoint.com/cgibin/printpage.cgi

191/225

8/12/2016

EntityFrameworkQuickGuide

NotMapped
BydefaultconventionsofCodeFirst,everypropertythatisofasupporteddatatypeandwhichincludesgetters
andsettersarerepresentedinthedatabase.Butthisisntalwaysthecaseinyourapplications.NotMapped
attributeoverridesthisdefaultconvention.Forexample,youmighthaveapropertyintheStudentclasssuchas
FatherName,butitdoesnotneedtobestored.YoucanapplyNotMappedattributetoaFatherNameproperty
whichyoudonotwanttocreateacolumnofinthedatabaseasshowninthefollowingcode.
publicclassStudent{
[Key]
publicintStdntID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}

publicDateTimeEnrollmentDate{get;set;}
[NotMapped]
publicintFatherName{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

YoucanseethatNotMappedattributeisappliedtotheFatherNameproperty.Whenthetableisgeneratedyou
willseethatFatherNamecolumnwillnotbecreatedinadatabase,butitispresentinStudentclass.

http://www.tutorialspoint.com/cgibin/printpage.cgi

192/225

8/12/2016

EntityFrameworkQuickGuide

CodeFirstwillnotcreateacolumnforaproperty,whichdoesnothaveeithergettersorsettersasshowninthe
followingexampleofAddressandAgepropertiesofStudentclass.

InverseProperty
InversePropertyisusedwhenyouhavemultiplerelationshipsbetweenclasses.IntheEnrollmentclass,youmay
wanttokeeptrackofwhoenrolledaCurrentCourseandPreviousCourse.Letsaddtwonavigationproperties
fortheEnrollmentclass.
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicGrade?Grade{get;set;}

publicvirtualCourseCurrCourse{get;set;}
publicvirtualCoursePrevCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}

Similarly,youllalsoneedtoaddintheCourseclassreferencedbytheseproperties.TheCourseclasshas
navigationpropertiesbacktotheEnrollmentclass,whichcontainsallthecurrentandpreviousenrollments.
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
[Index]
publicintCredits{get;set;}
publicvirtualICollection<Enrollment>CurrEnrollments{get;set;}
publicvirtualICollection<Enrollment>PrevEnrollments{get;set;}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

193/225

8/12/2016

EntityFrameworkQuickGuide

CodeFirstcreates{ClassName}_{PrimaryKey}foreignkeycolumn,iftheforeignkeypropertyisnotincluded
inaparticularclassasshownintheaboveclasses.Whenthedatabaseisgenerated,youwillseethefollowing
foreignkeys.

AsyoucanseethatCodefirstisnotabletomatchupthepropertiesinthetwoclassesonitsown.Thedatabase
tableforEnrollmentsshouldhaveoneforeignkeyfortheCurrCourseandoneforthePrevCourse,butCode
Firstwillcreatefourforeignkeyproperties,i.e.
CurrCourse_CourseID
PrevCourse_CourseID
Course_CourseID,and
Course_CourseID1
Tofixtheseproblems,youcanusetheInversePropertyannotationtospecifythealignmentoftheproperties.
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
[Index]
publicintCredits{get;set;}
[InverseProperty("CurrCourse")]
publicvirtualICollection<Enrollment>CurrEnrollments{get;set;}
[InverseProperty("PrevCourse")]
publicvirtualICollection<Enrollment>PrevEnrollments{get;set;}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

194/225

8/12/2016

EntityFrameworkQuickGuide

AsyoucanseetheInversePropertyattributeisappliedintheaboveCourseclassbyspecifyingwhichreference
propertyofEnrollmentclassitbelongsto.Now,CodeFirstwillgenerateadatabaseandcreateonlytwoforeign
keycolumnsinEnrollmentstableasshowninthefollowingimage.

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKFLUENTAPI
FluentAPIisanadvancedwayofspecifyingmodelconfigurationthatcoverseverythingthatdataannotations
candoinadditiontosomemoreadvancedconfigurationnotpossiblewithdataannotations.Dataannotations
andthefluentAPIcanbeusedtogether,butCodeFirstgivesprecedencetoFluentAPI>dataannotations>
defaultconventions.
FluentAPIisanotherwaytoconfigureyourdomainclasses.
TheCodeFirstFluentAPIismostcommonlyaccessedbyoverridingtheOnModelCreatingmethodon
yourderivedDbContext.
FluentAPIprovidesmorefunctionalityforconfigurationthanDataAnnotations.FluentAPIsupportsthe
followingtypesofmappings.
Inthischapter,wewillcontinuewiththesimpleexamplewhichcontainsStudent,CourseandEnrollmentclasses
andonecontextclasswithMyContextnameasshowninthefollowingcode.
usingSystem.Data.Entity;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceEFCodeFirstDemo{
classProgram{
staticvoidMain(string[]args){}

http://www.tutorialspoint.com/cgibin/printpage.cgi

195/225

8/12/2016

EntityFrameworkQuickGuide

publicenumGrade{
A,B,C,D,F
}
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicGrade?Grade{get;set;}

publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}

publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
publicintCredits{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassMyContext:DbContext{
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}
}

ToaccessFluentAPIyouneedtooverridetheOnModelCreatingmethodinDbContext.Letstakealookata
simpleexampleinwhichwewillrenamethecolumnnameinstudenttablefromFirstMidNametoFirstNameas
showninthefollowingcode.
publicclassMyContext:DbContext{
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
modelBuilder.Entity<Student>().Property(ss.FirstMidName)
.HasColumnName("FirstName");}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

DbModelBuilderisusedtomapCLRclassestoadatabaseschema.Itisthemainclassandonwhichyoucan
configureallyourdomainclasses.ThiscodecentricapproachtobuildinganEntityDataModelEDM isknown
asCodeFirst.

http://www.tutorialspoint.com/cgibin/printpage.cgi

196/225

8/12/2016

EntityFrameworkQuickGuide

FluentAPIprovidesanumberofimportantmethodstoconfigureentitiesanditspropertiestooverridevarious
CodeFirstconventions.Belowaresomeofthem.

Sr.No.
1

MethodName&Description
ComplexType<TComplexType>
Registersatypeasacomplextypeinthemodelandreturnsanobjectthatcanbeusedto
configurethecomplextype.Thismethodcanbecalledmultipletimesforthesametypeto
performmultiplelinesofconfiguration.

Entity<TEntityType>
Registersanentitytypeaspartofthemodelandreturnsanobjectthatcanbeusedto
configuretheentity.Thismethodcanbecalledmultipletimesforthesameentitytoperform
multiplelinesofconfiguration.

HasKey<TKey>
Configurestheprimarykeypropertysforthisentitytype.

HasMany<TTargetEntity>
Configuresamanyrelationshipfromthisentitytype.

HasOptional<TTargetEntity>
Configuresanoptionalrelationshipfromthisentitytype.Instancesoftheentitytypewillbe
abletobesavedtothedatabasewithoutthisrelationshipbeingspecified.Theforeignkeyin
thedatabasewillbenullable.

HasRequired<TTargetEntity>
Configuresarequiredrelationshipfromthisentitytype.Instancesoftheentitytypewillnot
beabletobesavedtothedatabaseunlessthisrelationshipisspecified.Theforeignkeyinthe
databasewillbenonnullable.

Ignore<TProperty>
Excludesapropertyfromthemodelsothatitwillnotbemappedtothedatabase.
I nheritedf romS tructuralT ypeC onf iguration < T S tructuralT ype >

http://www.tutorialspoint.com/cgibin/printpage.cgi

197/225

8/12/2016

EntityFrameworkQuickGuide

Property<T>
Configuresastructpropertythatisdefinedonthistype.
I nheritedf romS tructuralT ypeC onf iguration < T S tructuralT ype >

ToTableS tring
Configuresthetablenamethatthisentitytypeismappedto.

FluentAPIletsyouconfigureyourentitiesortheirproperties,whetheryouwanttochangesomethingabout
howtheymaptothedatabaseorhowtheyrelatetooneanother.There'sahugevarietyofmappingsand
modelingthatyoucanimpactusingtheconfigurations.FollowingarethemaintypesofmappingwhichFluent
APIsupports
EntityMapping
PropertiesMapping

EntityMapping
EntitymappingisjustsomesimplemappingsthatwillimpactEntityFramework'sunderstandingofhowthe
classesaremappedtothedatabases.Allthesewediscussedindataannotationsandherewewillseehowto
achievethesamethingsusingFluentAPI.
Soratherthangoingintothedomainclassestoaddtheseconfigurations,wecandothisinsideofthe
context.
ThefirstthingistooverridetheOnModelCreatingmethod,whichgivesthemodelBuildertoworkwith.

DefaultSchema
Thedefaultschemaisdbowhenthedatabaseisgenerated.YoucanusetheHasDefaultSchemamethodon
DbModelBuildertospecifythedatabaseschematouseforalltables,storedprocedures,etc.
Letstakealookatthefollowingexampleinwhichadminschemaisapplied.
publicclassMyContext:DbContext{
publicMyContext():base("name=MyContextDB"){}
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
}

publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

MapEntitytoTable

http://www.tutorialspoint.com/cgibin/printpage.cgi

198/225

8/12/2016

EntityFrameworkQuickGuide

Withdefaultconvention,CodeFirstwillcreatethedatabasetableswiththenameofDbSetpropertiesinthe
contextclasssuchasCourses,EnrollmentsandStudents.Butifyouwantdifferenttablenamesthenyoucan
overridethisconventionandcanprovideadifferenttablenamethantheDbSetproperties,asshowninthe
followingcode.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
//Mapentitytotable
modelBuilder.Entity<Student>().ToTable("StudentData");
modelBuilder.Entity<Course>().ToTable("CourseDetail");
modelBuilder.Entity<Enrollment>().ToTable("EnrollmentInfo");
}

Whenthedatabaseisgenerated,youwillseethetablesnameasspecifiedintheOnModelCreatingmethod.

EntitySplittingM apE ntitytoM ultipleT able


EntitySplittingletsyoucombinedatacomingfrommultipletablesintoasingleclassanditcanonlybeusedwith
tablesthathaveaonetoonerelationshipbetweenthem.Letstakealookatthefollowingexampleinwhich
Studentinformationismappedintotwotables.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");

http://www.tutorialspoint.com/cgibin/printpage.cgi

199/225

8/12/2016

EntityFrameworkQuickGuide

//Mapentitytotable
modelBuilder.Entity<Student>().Map(sd{
sd.Properties(pnew{p.ID,p.FirstMidName,p.LastName});
sd.ToTable("StudentData");
})
.Map(si{
si.Properties(pnew{p.ID,p.EnrollmentDate});
si.ToTable("StudentEnrollmentInfo");
});
modelBuilder.Entity<Course>().ToTable("CourseDetail");
modelBuilder.Entity<Enrollment>().ToTable("EnrollmentInfo");
}

Intheabovecode,youcanseethatStudententityissplitintothefollowingtwotablesbymappingsome
propertiestoStudentDatatableandsomepropertiestoStudentEnrollmentInfotableusingMapmethod.
StudentDataContainsStudentFirstMidNameandLastName.
StudentEnrollmentInfoContainsEnrollmentDate.
Whenthedatabaseisgeneratedyouseethefollowingtablesinyourdatabaseasshowninthefollowingimage.

PropertiesMapping
ThePropertymethodisusedtoconfigureattributesforeachpropertybelongingtoanentityorcomplextype.
ThePropertymethodisusedtoobtainaconfigurationobjectforagivenproperty.Youcanalsomapand
configurethepropertiesofyourdomainclassesusingFluentAPI.

http://www.tutorialspoint.com/cgibin/printpage.cgi

200/225

8/12/2016

EntityFrameworkQuickGuide

ConfiguringaPrimaryKey
Thedefaultconventionforprimarykeysare
ClassdefinesapropertywhosenameisIDorId
ClassnamefollowedbyIDorId
IfyourclassdoesntfollowthedefaultconventionsforprimarykeyasshowninthefollowingcodeofStudent
class
publicclassStudent{
publicintStdntID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Thentoexplicitlysetapropertytobeaprimarykey,youcanusetheHasKeymethodasshowninthefollowing
code
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");

//ConfigurePrimaryKey
modelBuilder.Entity<Student>().HasKey<int>(ss.StdntID);
}

ConfigureColumn
InEntityFramework,bydefaultCodeFirstwillcreateacolumnforapropertywiththesamename,order,and
datatype.Butyoucanalsooverridethisconvention,asshowninthefollowingcode.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
//ConfigureEnrollmentDateColumn
modelBuilder.Entity<Student>().Property(pp.EnrollmentDate)

.HasColumnName("EnDate")
.HasColumnType("DateTime")
.HasColumnOrder(2);
}

ConfigureMaxLengthProperty
Inthefollowingexample,theCourseTitlepropertyshouldbenolongerthan24characters.Whentheuser
specifiesvaluelongerthan24characters,thentheuserwillgetaDbEntityValidationExceptionexception.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
modelBuilder.Entity<Course>().Property(pp.Title).HasMaxLength(24);
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

201/225

8/12/2016

EntityFrameworkQuickGuide

ConfigureNullorNotNullProperty
Inthefollowingexample,theCourseTitlepropertyisrequiredsoIsRequiredmethodisusedtocreateNotNull
column.Similarly,StudentEnrollmentDateisoptionalsowewillbeusingIsOptionalmethodtoallowanull
valueinthiscolumnasshowninthefollowingcode.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
modelBuilder.Entity<Course>().Property(pp.Title).IsRequired();
modelBuilder.Entity<Student>().Property(pp.EnrollmentDate).IsOptional();

//modelBuilder.Entity<Student>().Property(ss.FirstMidName)
//.HasColumnName("FirstName");
}

ConfiguringRelationships
Arelationship,inthecontextofdatabases,isasituationthatexistsbetweentworelationaldatabasetables,
whenonetablehasaforeignkeythatreferencestheprimarykeyoftheothertable.WhenworkingwithCode
First,youdefineyourmodelbydefiningyourdomainCLRclasses.Bydefault,theEntityFrameworkusesthe
CodeFirstconventionstomapyourclassestothedatabaseschema.
IfyouusetheCodeFirstnamingconventions,inmostcasesyoucanrelyonCodeFirsttosetup
relationshipsbetweenyourtablesbasedontheforeignkeysandnavigationproperties.
Iftheydon'tmeetupwiththoseconventions,therearealsoconfigurationsyoucanusetoimpact
relationshipsbetweenclassesandhowthoserelationshipsarerealizedinthedatabasewhenyou're
addingconfigurationsinCodeFirst.
Someofthemareavailableinthedataannotationsandyoucanapplysomeevenmorecomplicatedones
withaFluentAPI.

ConfigureOnetoOneRelationship
Whenyoudefineaonetoonerelationshipinyourmodel,youuseareferencenavigationpropertyineachclass.
Indatabase,bothtablescanhaveonlyonerecordoneithersideoftherelationship.Eachprimarykeyvalue
relatestoonlyonerecordornorecordsintherelatedtable.
Aonetoonerelationshipiscreatedifbothoftherelatedcolumnsareprimarykeysorhaveunique
constraints.
Inaonetoonerelationship,theprimarykeyactsadditionallyasaforeignkeyandthereisnoseparate
foreignkeycolumnforeithertable.
Thistypeofrelationshipisnotcommonbecausemostinformationrelatedinthiswaywouldallbeinone
table.
Letstakealookatthefollowingexamplewherewewilladdanotherclassintoourmodeltocreateaonetoone
relationship.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

http://www.tutorialspoint.com/cgibin/printpage.cgi

202/225

8/12/2016

EntityFrameworkQuickGuide

publicvirtualStudentLogInStudentLogIn{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassStudentLogIn{
[Key,ForeignKey("Student")]
publicintID{get;set;}
publicstringEmailID{get;set;}
publicstringPassword{get;set;}

publicvirtualStudentStudent{get;set;}
}

AsyoucanseeintheabovecodethatKeyandForeignKeyattributesareusedforIDpropertyinStudentLogIn
class,inordertomarkitasPrimaryKeyaswellasForeignKey.
ToconfigureonetozerooronerelationshipbetweenStudentandStudentLogInusingFluentAPI,youneedto
overrideOnModelCreatingmethodasshowninthefollowingcode.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
//ConfigureIDasPKforStudentLogIn
modelBuilder.Entity<StudentLogIn>()
.HasKey(ss.ID);
//ConfigureIDasFKforStudentLogIn
modelBuilder.Entity<Student>()

.HasOptional(ss.StudentLogIn)//StudentLogInisoptional
.WithRequired(tt.Student);//Createinverserelationship
}

Inmostcases,theEntityFrameworkcaninferwhichtypeisthedependentandwhichistheprincipalina
relationship.However,whenbothendsoftherelationshiparerequiredorbothsidesareoptionaltheEntity
Frameworkcannotidentifythedependentandtheprincipal.Whenbothendsoftherelationshiparerequired,
youcanuseHasRequiredasshowninthefollowingcode.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
//ConfigureIDasPKforStudentLogIn
modelBuilder.Entity<StudentLogIn>()
.HasKey(ss.ID);
//ConfigureIDasFKforStudentLogIn
modelBuilder.Entity<Student>()
.HasRequired(rr.Student)
.WithOptional(ss.StudentLogIn);
}

Whenthedatabaseisgeneratedyouwillseethatrelationshipiscreatedasshowninthefollowingimage.

http://www.tutorialspoint.com/cgibin/printpage.cgi

203/225

8/12/2016

EntityFrameworkQuickGuide

ConfigureOnetoManyRelationship
Theprimarykeytablecontainsonlyonerecordthatrelatestonone,one,ormanyrecordsintherelatedtable.
Thisisthemostcommonlyusedtypeofrelationship.
Inthistypeofrelationship,arowintableAcanhavemanymatchingrowsintableB,butarowintableB
canhaveonlyonematchingrowintableA.
Theforeignkeyisdefinedonthetablethatrepresentsthemanyendoftherelationship.
Forexample,intheabovediagramStudentandEnrollmenttableshaveonetomanyrelationship,each
studentmayhavemanyenrollments,buteachenrollmentbelongstoonlyonestudent.
BelowaretheStudentandEnrollmentwhichhasonetomanyrelationship,buttheforeignkeyinEnrollment
tableisnotfollowingthedefaultCodeFirstconventions.
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}

//StdntIDisnotfollowingcodefirstconventionsname
publicintStdntID{get;set;}
publicGrade?Grade{get;set;}

publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}
publicclassStudent{
publicintID{get;set;}

http://www.tutorialspoint.com/cgibin/printpage.cgi

204/225

8/12/2016

EntityFrameworkQuickGuide

publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualStudentLogInStudentLogIn{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Inthiscase,toconfigureonetomanyrelationshipusingFluentAPI,youneedtouseHasForeignKeymethodas
showninthefollowingcode.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
//ConfigureFKforonetomanyrelationship
modelBuilder.Entity<Enrollment>()
.HasRequired<Student>(ss.Student)
.WithMany(tt.Enrollments)
.HasForeignKey(uu.StdntID);
}

Whenthedatabaseisgeneratedyouwillseethattherelationshipiscreatedasshowninthefollowingimage.

Intheaboveexample,theHasRequiredmethodspecifiesthattheStudentnavigationpropertymustbeNull.So
youmustassignStudentwithEnrollmententityeverytimeyouaddorupdateEnrollment.Tohandlethiswe
needtouseHasOptionalmethodinsteadofHasRequiredmethod.

http://www.tutorialspoint.com/cgibin/printpage.cgi

205/225

8/12/2016

EntityFrameworkQuickGuide

ConfigureManytoManyRelationship
Eachrecordinbothtablescanrelatetoanynumberofrecordsornorecordsintheothertable.
Youcancreatesucharelationshipbydefiningathirdtable,calledajunctiontable,whoseprimarykey
consistsoftheforeignkeysfrombothtableAandtableB.
Forexample,theStudenttableandtheCoursetablehavemanytomanyrelationship.
FollowingaretheStudentandCourseclassesinwhichStudentandCoursehasmanytomanyrelationship,
becausebothclasseshavenavigationpropertiesStudentsandCoursesthatarecollections.Inotherwords,one
entityhasanotherentitycollection.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Course>Courses{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
publicintCredits{get;set;}

publicvirtualICollection<Student>Students{get;set;}
publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

ToconfiguremanytomanyrelationshipbetweenStudentandCourse,youcanuseFluentAPIasshowninthe
followingcode.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
//Configuremanytomanyrelationship
modelBuilder.Entity<Student>()
.HasMany(ss.Courses)
.WithMany(ss.Students);
}

ThedefaultCodeFirstconventionsareusedtocreateajointablewhendatabaseisgenerated.Asaresult,the
StudentCoursestableiscreatedwithCourse_CourseIDandStudent_IDcolumnsasshowninthefollowing
image.

http://www.tutorialspoint.com/cgibin/printpage.cgi

206/225

8/12/2016

EntityFrameworkQuickGuide

Ifyouwanttospecifythejointablenameandthenamesofthecolumnsinthetableyouneedtodoadditional
configurationbyusingtheMapmethod.
protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){
//Configuredefaultschema
modelBuilder.HasDefaultSchema("Admin");
//Configuremanytomanyrelationship
modelBuilder.Entity<Student>()
.HasMany(ss.Courses)
.WithMany(ss.Students)

.Map(m{
m.ToTable("StudentCoursesTable");
m.MapLeftKey("StudentID");
m.MapRightKey("CourseID");
});
}

Youcanseewhenthedatabaseisgenerated,thetableandcolumnsnamearecreatedasspecifiedintheabove
code.

http://www.tutorialspoint.com/cgibin/printpage.cgi

207/225

8/12/2016

EntityFrameworkQuickGuide

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKSEEDDATABASE
InEntityFramework,SeedwasintroducedinEF4.1andworkswithdatabaseinitializers.Thegeneralideaofa
SeedMethodistoinitializedataintoadatabasethatisbeingcreatedbyCodeFirstorevolvedbyMigrations.
Thisdataisoftentestdata,butmayalsobereferencedatasuchaslistsofknownStudents,Courses,etc.When
thedataisinitialized,itdoesthefollowing
Checkswhetherornotthetargetdatabasealreadyexists.
Ifitdoes,thenthecurrentCodeFirstmodeliscomparedwiththemodelstoredinmetadatainthe
database.
Thedatabaseisdroppedifthecurrentmodeldoesnotmatchthemodelinthedatabase.
Thedatabaseiscreatedifitwasdroppedordidntexistinthefirstplace.
Ifthedatabasewascreated,thentheinitializerSeedmethodiscalled.
TheSeedmethodtakesthedatabasecontextobjectasaninputparameter,andthecodeinthemethodusesthat
objecttoaddnewentitiestothedatabase.Toseeddataintoyourdatabase,youneedtooverridetheSeed
method.Letstakealookatthefollowingexampleinwhichsomeofthedefaultdataareinitiatedintothe
databaseinaninternalclass.
privateclassUniDBInitializer<T>:DropCreateDatabaseAlways<MyContext>{
protectedoverridevoidSeed(MyContextcontext){
IList<Student>students=newList<Student>();

http://www.tutorialspoint.com/cgibin/printpage.cgi

208/225

8/12/2016

EntityFrameworkQuickGuide

students.Add(newStudent(){
FirstMidName="Andrew",
LastName="Peters",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
});
students.Add(newStudent(){
FirstMidName="Brice",
LastName="Lambson",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
});
students.Add(newStudent(){
FirstMidName="Rowan",
LastName="Miller",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
});
foreach(Studentstudentinstudents)
context.Students.Add(student);
base.Seed(context);
}
}

Intheabovecode,studenttableisinitialized.YouneedtosetthisDBinitializerclassincontextclassasshownin
thefollowingcode.
publicMyContext():base("name=MyContextDB"){
Database.SetInitializer<MyContext>(newUniDBInitializer<MyContext>());
}

FollowingisthecompleteclassimplementationofMyContextclass,whichalsocontainstheDBinitializerclass.
publicclassMyContext:DbContext{
publicMyContext():base("name=MyContextDB"){
Database.SetInitializer<MyContext>(newUniDBInitializer<MyContext>());
}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}

privateclassUniDBInitializer<T>:DropCreateDatabaseAlways<MyContext>{
protectedoverridevoidSeed(MyContextcontext){
IList<Student>students=newList<Student>();

students.Add(newStudent(){
FirstMidName="Andrew",
LastName="Peters",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
});
students.Add(newStudent(){
FirstMidName="Brice",
LastName="Lambson",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
});

http://www.tutorialspoint.com/cgibin/printpage.cgi

209/225

8/12/2016

EntityFrameworkQuickGuide

students.Add(newStudent(){
FirstMidName="Rowan",
LastName="Miller",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
});
foreach(Studentstudentinstudents)
context.Students.Add(student);
base.Seed(context);
}
}
}

Whentheaboveexampleiscompiledandexecuted,youcanseethedatainadatabaseasshowninthefollowing
image.

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKCODEFIRSTMIGRATION
EntityFramework4.3includesanewCodeFirstMigrationsfeaturethatallowsyoutoincrementallyevolvethe
databaseschemaasyourmodelchangesovertime.Formostdevelopers,thisisabigimprovementoverthe
databaseinitializeroptionsfromthe4.1and4.2releasesthatrequiredyoutomanuallyupdatethedatabaseor
dropandrecreateitwhenyourmodelchanged.
BeforeEntityFramework4.3,ifyoualreadyhavedataotherthanseeddataorexistingStoredProcedures,
triggers,etc.inyourdatabase,thesestrategiesusedtodroptheentiredatabaseandrecreateit,soyou
wouldlosethedataandotherDBobjects.

http://www.tutorialspoint.com/cgibin/printpage.cgi

210/225

8/12/2016

EntityFrameworkQuickGuide

Withmigration,itwillautomaticallyupdatethedatabaseschema,whenyourmodelchangeswithout
losinganyexistingdataorotherdatabaseobjects.
ItusesanewdatabaseinitializercalledMigrateDatabaseToLatestVersion.
TherearetwokindsofMigration
AutomatedMigration
CodebasedMigration

AutomatedMigration
AutomatedMigrationwasfirstintroducedinEntityframework4.3.Inautomatedmigrationyoudon'tneedto
processdatabasemigrationmanuallyinthecodefile.Forexample,foreachchangeyouwillalsoneedtochange
inyourdomainclasses.ButwithautomatedmigrationyoujusthavetorunacommandinPackageManager
Consoletogetdonethis.
Letstakealookatthefollowingstepbystepprocessofautomatedmigration.
WhenyouuseCodeFirstapproach,youdon'thaveadatabaseforyouapplication.
Inthisexamplewewillbestartingwithour3basicclassessuchasStudent,CourseandEnrollmentasshownin
thefollowingcode.
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicGrade?Grade{get;set;}

publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
[Index]
publicintCredits{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Followingisthecontextclass.
publicclassMyContext:DbContext{
publicMyContext():base("MyContextDB"){}
publicvirtualDbSet<Course>Courses{get;set;}

http://www.tutorialspoint.com/cgibin/printpage.cgi

211/225

8/12/2016

EntityFrameworkQuickGuide

publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

Beforerunningtheapplication,youneedtoenableautomatedmigration.
Step1OpenPackageMangerConsolefromToolsNuGetPackageMangerPackageMangerConsole.
Step2ToenableautomatedmigrationrunthefollowingcommandinPackageManagerConsole.
PM>enablemigrationsEnableAutomaticMigrations:$true

Step3Oncethecommandrunssuccessfully,itcreatesaninternalsealedConfigurationclassintheMigration
folderofyourprojectasshowninthefollowingcode.
namespaceEFCodeFirstDemo.Migrations{
usingSystem;
usingSystem.Data.Entity;
usingSystem.Data.Entity.Migrations;
usingSystem.Linq;

internalsealedclassConfiguration:DbMigrationsConfiguration<EFCodeFirstDemo.MyContext>
{
publicConfiguration(){
AutomaticMigrationsEnabled=true;
ContextKey="EFCodeFirstDemo.MyContext";
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

212/225

8/12/2016

EntityFrameworkQuickGuide

protectedoverridevoidSeed(EFCodeFirstDemo.MyContextcontext){
//Thismethodwillbecalledaftermigratingtothelatestversion.
//YoucanusetheDbSet<T>.AddOrUpdate()helperextensionmethod
//toavoidcreatingduplicateseeddata.E.g.
//context.People.AddOrUpdate(
//pp.FullName,
//newPerson{FullName="AndrewPeters"},
//newPerson{FullName="BriceLambson"},
//newPerson{FullName="RowanMiller"}
//);
}
}
}

Step4SetthedatabaseinitializerinthecontextclasswiththenewDBinitializationstrategy
MigrateDatabaseToLatestVersion.
publicclassMyContext:DbContext{
publicMyContext():base("MyContextDB"){
Database.SetInitializer(newMigrateDatabaseToLatestVersion<MyContext,
EFCodeFirstDemo.Migrations.Configuration>("MyContextDB"));
}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

Step5Youhavesetupautomatedmigration.Whenyouexecuteyourapplication,thenitwillautomatically
takecareofmigration,whenyouchangethemodel.

http://www.tutorialspoint.com/cgibin/printpage.cgi

213/225

8/12/2016

EntityFrameworkQuickGuide

Step6Asyoucanseethatonesystemtable__MigrationHistoryisalsocreatedinyourdatabasewithother
tables.In__MigrationHistory,automatedmigrationmaintainsthehistoryofdatabasechanges.
Step7Whenyouaddanotherentityclassasyourdomainclassandexecuteyourapplication,thenitwill
createthetableinyourdatabase.LetsaddthefollowingStudentLogInclass.
publicclassStudentLogIn{
[Key,ForeignKey("Student")]
publicintID{get;set;}
publicstringEmailID{get;set;}
publicstringPassword{get;set;}

publicvirtualStudentStudent{get;set;}
}

Step8DontforgettoaddtheDBSetfortheabovementionedclassinyourcontextclassasshowninthe
followingcode.
publicvirtualDbSet<StudentLogIn>StudentsLogIn{get;set;}

Step9RunyourapplicationagainandyouwillseethatStudentsLogIntableisaddedtoyourdatabase.

http://www.tutorialspoint.com/cgibin/printpage.cgi

214/225

8/12/2016

EntityFrameworkQuickGuide

Theabovestepsmentionedforautomatedmigrationswillonlyworkforyourentity.Forexample,toadd
anotherentityclassorremovetheexistingentityclassitwillsuccessfullymigrate.Butifyouaddorremoveany
propertytoyourentityclassthenitwillthrowanexception.
Step10TohandlethepropertymigrationyouneedtosetAutomaticMigrationDataLossAllowed=trueinthe
configurationclassconstructor.
publicConfiguration(){
AutomaticMigrationsEnabled=true;
AutomaticMigrationDataLossAllowed=true;
ContextKey="EFCodeFirstDemo.MyContext";
}

CodeBasedMigration
Whenyoudevelopanewapplication,yourdatamodelchangesfrequently,andeachtimethemodelchanges,it
getsoutofsyncwiththedatabase.YouhaveconfiguredtheEntityFrameworktoautomaticallydropandre
createthedatabaseeachtimeyouchangethedatamodel.Codebasedmigrationisusefulwhenyouwantmore
controlonthemigration.
Whenyouadd,remove,orchangeentityclassesorchangeyourDbContextclass,thenexttimeyourun
theapplicationitautomaticallydeletesyourexistingdatabase,createsanewonethatmatchesthemodel,
andseedsitwithtestdata.
TheCodeFirstMigrationsfeaturesolvesthisproblembyenablingCodeFirsttoupdatethedatabase
schemainsteadofdroppingandrecreatingthedatabase.Todeploytheapplication,you'llhavetoenable
Migrations.
Hereisthebasicruletomigratechangesinthedatabase
EnableMigrations

http://www.tutorialspoint.com/cgibin/printpage.cgi

215/225

8/12/2016

EntityFrameworkQuickGuide

AddMigration
UpdateDatabase
Letstakealookatthefollowingstepbystepprocessofcodebasemigration.
Whenyouusecodefirstapproach,youdon'thaveadatabaseforyouapplication.
Inthisexamplewewillbestartingagainwithour3basicclassessuchasStudent,CourseandEnrollmentas
showninthefollowingcode.
publicclassEnrollment{
publicintEnrollmentID{get;set;}
publicintCourseID{get;set;}
publicintStudentID{get;set;}
publicGrade?Grade{get;set;}

publicvirtualCourseCourse{get;set;}
publicvirtualStudentStudent{get;set;}
}
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassCourse{
publicintCourseID{get;set;}
publicstringTitle{get;set;}
[Index]
publicintCredits{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

Followingisthecontextclass.
publicclassMyContext:DbContext{
publicMyContext():base("MyContextDB"){
Database.SetInitializer(newMigrateDatabaseToLatestVersion<
MyContext,EFCodeFirstDemo.Migrations.Configuration>("MyContextDB"));
}
publicvirtualDbSet<Course>Courses{get;set;}
publicvirtualDbSet<Enrollment>Enrollments{get;set;}
publicvirtualDbSet<Student>Students{get;set;}
}

Step1Beforerunningtheapplicationyouneedtoenablemigration.
Step2OpenPackageManagerConsolefromToolsNuGetPackageMangerPackageMangerConsole.

http://www.tutorialspoint.com/cgibin/printpage.cgi

216/225

8/12/2016

EntityFrameworkQuickGuide

Step3Migrationisalreadyenabled,nowaddmigrationinyourapplicationbyexecutingthefollowing
command.
PM>addmigration"UniDBSchema"

Step4Whenthecommandissuccessfullyexecutedthenyouwillseeanewfilehasbeencreatedinthe
Migrationfolderwiththenameoftheparameteryoupassedtothecommandwithatimestampprefixasshown
inthefollowingimage.

Step5Youcancreateorupdatethedatabaseusingtheupdatedatabasecommand.
PM>UpdateDatabaseVerbose

The"Verbose"flagspecifiestoshowtheSQLStatementsbeingappliedtothetargetdatabaseintheconsole.
Step6LetsaddonemorepropertyAgeinthestudentclassandthenexecutetheupdatestatement.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicintAge{get;set;}
publicDateTimeEnrollmentDate{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

217/225

8/12/2016

EntityFrameworkQuickGuide

WhenyouexecutePMUpdateDatabaseVerbose,whenthecommandissuccessfullyexecutedyouwillsee
thatthenewcolumnAgeisaddedinyourdatabase.

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKMULTIPLEDBCONTEXT
Inthischapter,wewillbelearninghowtomigratechangesintothedatabasewhentherearemultipleDbContext
classesintheapplication.
MultipleDbContextwasfirstintroducedinEntityFramework6.0.
Multiplecontextclassesmaybelongtoasingledatabaseortwodifferentdatabases.
Inourexample,wewilldefinetwoContextclassesforthesamedatabase.Inthefollowingcode,therearetwo
DbContextclassesforStudentandTeacher.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}
}
publicclassMyStudentContext:DbContext{
publicMyStudentContext():base("UniContextDB"){}
publicvirtualDbSet<Student>Students{get;set;}
}
publicclassTeacher{

http://www.tutorialspoint.com/cgibin/printpage.cgi

218/225

8/12/2016

EntityFrameworkQuickGuide

publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeHireDate{get;set;}
}
publicclassMyTeacherContext:DbContext{
publicMyTeacherContext():base("UniContextDB"){}
publicvirtualDbSet<Teacher>Teachers{get;set;}
}

Asyoucanseeintheabovecode,therearetwomodelscalledStudentandTeacher.Eachoneisassociated
withaparticularcorrespondingcontextclass,i.e.,StudentisassociatedwithMyStudentContextandTeacheris
associatedwithMyTeacherContext.
Hereisthebasicruletomigratechangesindatabase,whentherearemultipleContextclasseswithinthesame
project.
enablemigrationsContextTypeName<DbContextNamewithNamespaces>MigrationsDirectory:
<MigrationsDirectoryName>
AddMigrationconfiguration<DbContextMigrationsConfigurationClasswithNamespaces>
<MigrationsName>
UpdateDatabaseconfiguration<DbContextMigrationsConfigurationClasswithNamespaces>
Verbose
LetsenablemigrationforMyStudentContextbyexecutingthefollowingcommandinPackageManager
Console.
PMenablemigrationsContextTypeName:EFCodeFirstDemo.MyStudentContext

http://www.tutorialspoint.com/cgibin/printpage.cgi

219/225

8/12/2016

EntityFrameworkQuickGuide

Onceitisexecuted,wewilladdthemodelinthemigrationhistoryandforthat,wehavetofireaddmigration
commandinthesameconsole.
PMaddmigrationconfigurationEFCodeFirstDemo.Migrations.ConfigurationInitial

LetusnowaddsomedataintoStudentsandTeacherstablesinthedatabase.
staticvoidMain(string[]args){
using(varcontext=newMyStudentContext()){

////CreateandsaveanewStudents
Console.WriteLine("Addingnewstudents");
varstudent=newStudent{
FirstMidName="Alain",
LastName="Bomer",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
//Age=24
};
context.Students.Add(student);
varstudent1=newStudent{
FirstMidName="Mark",
LastName="Upston",
EnrollmentDate=DateTime.Parse(DateTime.Today.ToString())
//Age=30
};
context.Students.Add(student1);
context.SaveChanges();
//DisplayallStudentsfromthedatabase
varstudents=(fromsincontext.Studentsorderbys.FirstMidName
selects).ToList<Student>();

Console.WriteLine("RetrieveallStudentsfromthedatabase:");
foreach(varstdntinstudents){
stringname=stdnt.FirstMidName+""+stdnt.LastName;
Console.WriteLine("ID:{0},Name:{1}",stdnt.ID,name);
}
Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}
using(varcontext=newMyTeacherContext()){
////CreateandsaveanewTeachers
Console.WriteLine("Addingnewteachers");
varstudent=newTeacher{
FirstMidName="Alain",
LastName="Bomer",
HireDate=DateTime.Parse(DateTime.Today.ToString())
//Age=24
};
context.Teachers.Add(student);

http://www.tutorialspoint.com/cgibin/printpage.cgi

220/225

8/12/2016

EntityFrameworkQuickGuide

varstudent1=newTeacher{
FirstMidName="Mark",
LastName="Upston",
HireDate=DateTime.Parse(DateTime.Today.ToString())
//Age=30
};
context.Teachers.Add(student1);
context.SaveChanges();

//DisplayallTeachersfromthedatabase
varteachers=(fromtincontext.Teachersorderbyt.FirstMidName
selectt).ToList<Teacher>();

Console.WriteLine("Retrieveallteachersfromthedatabase:");
foreach(varteacherinteachers){
stringname=teacher.FirstMidName+""+teacher.LastName;
Console.WriteLine("ID:{0},Name:{1}",teacher.ID,name);
}
Console.WriteLine("Pressanykeytoexit...");
Console.ReadKey();
}
}

Whentheabovecodeisexecuted,youwillseethattwodifferenttablesarecreatedfortwodifferentmodelsas
showninthefollowingimage.

Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

ENTITYFRAMEWORKNESTEDENTITYTYPES

http://www.tutorialspoint.com/cgibin/printpage.cgi

221/225

8/12/2016

EntityFrameworkQuickGuide

PriortoEntityFramework6,EntityFrameworkdidn'trecognizeentitiesorcomplextypesthatwerenested
withinotherentitiesorcomplextypes.WhenEntityFrameworkgeneratedthemodel,thenestedtypesjust
disappeared.
LetstakealookatasimpleexampleinwhichwehaveourbasicmodelwiththreeentitiesStudent,Courseand
Enrollment.
LetsaddapropertyIdentity,whichisaPersontype.Personisanotherentity,containsBirthDateand
FatherNameproperties.
InEntityFrameworkterms,becauseithasnoidentityandispartofanentity,it'sanEntityFramework
complextype,andwe'veactuallyhadsupportforcomplextypessincethefirstversionofEntity
Framework.
ThePersontypeisn'tnestedasshowninthefollowingcode.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}
publicDateTimeEnrollmentDate{get;set;}
publicPersonIdentity{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
}
publicclassPerson{
publicPerson(stringfatherName,DateTimebirthDate){
FatherName=fatherName;
BirthDate=birthDate;
}

publicstringFatherName{get;set;}
publicDateTimeBirthDate{get;set;}
}

EntityFrameworkwillknowhowtopersistPersontypeswhenitisusedinpreviousversionsaswell.
ByusingEntityFrameworkPowerToolwewillseehowEntityFrameworkinterpretsthemodel.Rightclickon
Program.csfileandselectEntityFrameworkViewEntityDataModelReadonly

http://www.tutorialspoint.com/cgibin/printpage.cgi

222/225

8/12/2016

EntityFrameworkQuickGuide

NowyouwillseethatIdentitypropertyisdefinedinStudentclass.

IfthisPersonclasswon'tbeusedbyanyotherentity,thenwecannestitinsidetheStudentclass,butthisearlier
versionofEntityFrameworkdoesn'tacknowledgenestedtypes.

http://www.tutorialspoint.com/cgibin/printpage.cgi

223/225

8/12/2016

EntityFrameworkQuickGuide

Inolderversion,yougeneratethemodelagain,notonlyisthetypenotrecognized,butbecauseit'snotthere,
thepropertyisn'tthereeither,soEntityFrameworkwon'tpersistthePersontypeatall.
publicclassStudent{
publicintID{get;set;}
publicstringLastName{get;set;}
publicstringFirstMidName{get;set;}

publicDateTimeEnrollmentDate{get;set;}
publicPersonIdentity{get;set;}

publicvirtualICollection<Enrollment>Enrollments{get;set;}
publicclassPerson{
publicPerson(stringfatherName,DateTimebirthDate){
FatherName=fatherName;
BirthDate=birthDate;
}
publicstringFatherName{get;set;}
publicDateTimeBirthDate{get;set;}
}
}

WithEntityFramework6,nestedentitiesandcomplextypesarerecognized.Intheabovecode,youcanseethat
PersonisnestedwithintheStudentclass.
WhenyouusetheEntityFrameworkPowerTooltoshowhowEntityFrameworkinterpretsthemodelthistime,
there'strueIdentityproperty,andPersoncomplextype.SoEntityFrameworkwillpersistthatdata.

http://www.tutorialspoint.com/cgibin/printpage.cgi

224/225

8/12/2016

EntityFrameworkQuickGuide

NowyoucanseethatIdentityisanestedentitytype,whichwasnotsupportedbeforeEntityFramework6.
Werecommendthatyouexecutetheaboveexampleinastepbystepmannerforbetterunderstanding.

http://www.tutorialspoint.com/cgibin/printpage.cgi

225/225

You might also like