Entity Framework

auburnhairSoftware and s/w Development

Dec 13, 2013 (4 years and 7 months ago)


Code First queries DB and performs CRUD

Relies on DBContext: create standard .NET classes, add in properties

These classes interact with DBContext class and DB tables are generated

Install Nuget: Tools/ExtensionManager/Online Gallery/Nuget

Run Packa
ge Manager: Right
click on References in solution/Add Library Package
Reference/Online/Nuget official package source

Type “EntityFramework” in upper right search box

If error message, Tools/Library Package Manager/Package Manager Console

At console PM> Ins
Package EntityFramework

Download EF4.1, putting references in solution

Write classes first:

Add context class by righ
clicking on solution/Add

Derive class from DbContext (:DbContext) and resolve

Add connection string info to web.config

/Add/Class/name it “…Repository” as a suffix to create an .aspx page to run EF

Create c
lass to query against DbContext (can add CRUD queries here)

Design a GridView hooked up to an ObjectDataSource

DataSource on smart tag



When Classes Change

Go to Database Explorer/Database Connections/Add a Connection/MS SQL Server

Now can see two new tables in DB Explorer with added foreign key ID (i.e., Employee_ID)

EdmMetaData created (ID and hash table to track changes in the DB)

ually add Employees to table:

When Classes Change

Just manually adding new properties, get following error:


Solution/Add/New Item/Global Application Class/leave name Global.asax: universal class that
initializes application, ses
sion, requests, etc. In Global.asax:

Generic name is dbContext filename from solution

Resolve namespace

.aspx will show that
but with data
dropped and recreated

Refresh table in DB Explorer, will show new properties or other changes

Comment out c
ode in Global.asax

Solution Explorer/Models/Add/Class

Call … DBContextInitializer

(Missing end bracket above)

Last two lines iterate through employees and add them to DB

Base.Seed updates DB to take care of updating objects automatically

[In DB Explorer,

click on table name and can view table data]

In Global.asax, reinstate Database.SetInitializer with new class created above

Be sure to close DB Explorer connection before making changes to classes and running them

LINQ Queries

Performs queries a
inst objects or (Code First) DBContext

LINQ queries generat

SQL statement

Returns object called IQueryable

Lambda code alternative

GetEmployeeCount() is an aggregate function that uses extension method .Count

Variation using lambda and extension me
thod .Average() below

Filtering Data

Filtering queries in EF run in database, much more efficient than retrieving all data and then

Added method with error caused by
incompatible type between IQueryable and generic list:

Solved by adding
.SingleorDefault(), which returns the first collection encountered (in this case
the only one) or, if none found, NULL if specified as default: