SlideShare a Scribd company logo
James Johnson, MVP
   Founder and President of the Inland Empire .NET
    User’s Group

   Three time and current Microsoft MVP – CAD

   Software developer by day

   Serial netrepreneur by night
Entity Framework Database and Code First
   Entity Framework
   Database First
   Code First
   MVC Scaffolding
   Version 4 released with .NET 4.0
   New version (4.3) allows for model-first, code-first
    or database-first development
   Maps POCO objects to database objects
   A collection of things instead of a dataset of rows
   “things” are the entities
   Why?
    ◦ Adds a layer of abstraction between database and
      code
    ◦ DBA can structure database how they want
    ◦ Developer can map to the database how they want
    ◦ Rename entities for more comfortable use
    ◦ Entity Framework handles the mappings
   Entity Data Model – EDM
    ◦ Deals with the entities and relationships they use
   Entities
    ◦ Instance of EntityType
      Specification for a data type which includes a key and
       named set of properties
    ◦ Represent individual instances of the objects
    ◦ Customer, book, shoe, usergroup
    ◦ Fully typed
   Relationships between look up tables are mapped
    as associations in the EDMX
   csdl
    ◦ Conceptual Schema Definition Language
    ◦ The conceputal schema for the EDM
    ◦ EntityContainer, EntitySet, EntityType definitions
   ssdl
    ◦ Store Schema Definition Language
    ◦ Schematic representation of the data store
   msl
    ◦ Mapping Specification Language
    ◦ Sits between the csdl and ssdl and maps the entity
      properties
Lazy Loading
A design pattern to defer initialization until needed

context.ContextOptions.DeferredLoadingEnabled=true;
List<Member> members = context.Members.ToList();
foreach(var member in members)
{
  var memberBooks = member.Books;
}
Eager Loading
Use if you will be needing every related entity

List<Member> Members =
  context.Members.Include(“Books”).ToList();

foreach(var member in members)
{
  var memberBooks = member.Books;
}
Contexts
   The context is the instance of the entity
   Passing an entity around to tiers breaks the context
   Just like the song, make sure the context remains
    the same
Contexts
public class ModelHelper
{
   private static Entities _db;
   public static Entities Entities
   {
       get
       {
           if(_db == null)
             _db = new Entities();
             return _db;
           }
           set { _db = value; }
       }
   }
private readonly Entities _db = new Entities();
Contexts
private Member AddMember(Member member, UserGroup group)
{
    member.UserGroups.Add(group);
    _db.SaveChanges();
}
  Doesn’t work because group is in a different context

private Member AddMember(Member member, UserGroup group)
{
    var newMember = GetMember(member.Id);
    var newGroup = GetUserGroup(group.Id);
    newMember.UserGroups.Add(newGroup);
    _db.SaveChanges();
}
LINQ to Entities
Very similar to LINQ to SQL

Selecting
Member member = _db.Members.Single(x=>x.Id == id);

Deleting
public void DeleteMember(Member member)
{
  _db.DeleteObject(member);
  _db.SaveChanges();
}
LINQ to Entities
Adding (Inserting)
public void AddMember(Member member)
{
   _db.AddToMembers(member)    //this will be a list
   _db.SaveChanges()           // of AddTo<Entities>
}

Editing (Updating)
public void EditMember(Member member)
{
   _db.Members.Attach(new Member{Id=member.Id});
   _db.Members.ApplyCurrentValues(member);
   _db.SaveChanges();
}
Repositories
   Repository pattern encapsulates code into a separate class
   Allows for easy changes
   Can use it to switch database providers or new technologies
   Stephen Walther – ASP.NET MVC Framework, Sams
    ◦ stephenwalther.com
    ◦ “Download the code” link
   Add the two projects to your solution
   Add references to your project
Repositories
using GenericRepository
public class MyController
{
   private readonly IGenericRepository _repo;
   private readonly Entities _db;

    public MyController()
    {
      _repo = new
       EFGenericRepository.EFGenericRepository(_db);
    }
}
Repositories
_repo.Get<Member>(id); // get

_repo.Edit(member); // edit

_repo.Create(member); // create

_repo.Delete(member); // delete

// list
var list = _repo.List<Member>().Where(x =>
        x.Name.Contains(myName));
Database First
   Create the database first
   Build tables and relationships
   Create Entity Data Model (EDMX) in Visual Studio
   Look up tables are converted to Associations
Database First
Database First




    Members_Books           UserGroups_Members


       Associations representing look up tables
Demo
Code First – The “Magic Unicorn”
   Write code without having to define mappings in XML
   Define objects in POCO
   No base classes required
   Enables database persistence with no configuration
   Can use Data Annotations
    ◦   Key
    ◦   StringLength
    ◦   Required
    ◦   RelatedTo
    ◦   Etc.
   DbContext
    ◦ Primary object to interact with a database using specific model
   DbSet<TEntity>
    ◦ Used to perform CRUD against a specific type from the model
Code First
   Create classes
   Create Context
   Create Controller
   Write code for
    ◦   Select
    ◦   Add
    ◦   Update
    ◦   Delete
   Create Views
Databases
    By default, creates SQL Express DB
     ◦ <Project>.Models.<Project>Context.mdf
    Can switch to SQL Compact

1.    NuGet
2.    Search for SqlServerCompact
3.    Install

Adds System.Data.SqlServerCe to references
Databases
     Add connection string settings to web.config
     Name needs to match context

<add name=“UserGroups”
connectionString=“Data Source=|DataDirectory|UserGroups.sdf”
providerName=“System.Data.SqlServerCe.4.0” />
Databases
   Run the project
   UserGroups.sdf will be created
Databases – Keeping Current
   Modifying the database
   Add setting to Global.asax




   Implementation of IDatabaseInitializer
   Deletes and recreates the database
Databases – Keeping Current
   EF 4.3.1 uses Code First Migrations
    ◦ Enabled by default
    ◦ Adds table __MigrationHistory to database
   Only modifies database if model has changed
Demo
Scaffolding
   Create MVC project
   Use NuGet to update EntityFramework
   Package Manager Console “Install-Package MvcScaffolding”
Scaffolding
   Add Class(es)
   Build Project
Scaffolding
   Package Manager Console
   “Scaffold Controller <ClassName>
Scaffolding
   Controller and Views are created
Scaffolding – Other Commands
   -ControllerName
    ◦ UserGroupsController – look for class “UserGroup”
    ◦ UserGroup – creates UserGroupsController
   -ModelType
    ◦ Inferred from controller name
    ◦ Can change name of the model if needed
   -Project
    ◦ Specify the name of the project in multi-project solutions
   -CodeLanguage
    ◦ Specify “cs” or “vb”
   -DbContextType
    ◦ Specify the name of the context
Scaffolding – Other Commands
   -Repository
    ◦ Switch. Will generate a repository class for data access
   -Area
    ◦ For putting the generated files in a specific MVC Area
   -Layout
    ◦ Which layout page to use if not default _Layout.cshtml
   -Force
    ◦ Forces overwriting of existing files
   -NoChildItems
    ◦ Will only generate the controller, no views, repositories or data
      contexts
Scaffolding
     Add connection string settings to web.config
     Name needs to match context

<add name=“UserGroupsScaffoldingContext”
connectionString=“Data Source=|DataDirectory|UserGroups.sdf”
providerName=“System.Data.SqlServerCe.4.0” />
Scaffolding
   Run the project
   Navigate to /UserGroups/
   Database is created
Scaffolding
   Scaffold the rest of the classes
   “Scaffold Controller <ClassName>




   Run the project
   Database will be modified with new tables
Scaffolding
Scaffolding Relationships
   It’s not you, it’s me.
   Add relationships to your classes




                                        Using virtual allows EF to
                                        use Lazy Loading
Scaffolding Relationships
   Run the project again
   Database is modified




         Look up tables
           are created
Entity Framework Database and Code First
   Slides are at
    ◦ http://slidesha.re/EFScaffolding
   Inland Empire .NET User’s Group
    ◦ 2nd Tuesday of each month
    ◦ www.iedotnetug.org
   james@iedotnetug.org
   @latringo

More Related Content

What's hot (20)

Dfd
DfdDfd
Dfd
rodrigobarriauribe
 
Diagramas De Despligue Uml
Diagramas De Despligue UmlDiagramas De Despligue Uml
Diagramas De Despligue Uml
arcangelsombra
 
Les03 Single Row Function
Les03 Single Row FunctionLes03 Single Row Function
Les03 Single Row Function
NETsolutions Asia: NSA – Thailand, Sripatum University: SPU
 
Clean code: SOLID (iOS)
Clean code: SOLID (iOS)Clean code: SOLID (iOS)
Clean code: SOLID (iOS)
Maksym Husar
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
José Paumard
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScriptLotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Bill Buchan
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
NexThoughts Technologies
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
Nicole Ryan
 
Herramientas CASE
Herramientas CASEHerramientas CASE
Herramientas CASE
I R
 
Introduce yourself to java 17
Introduce yourself to java 17Introduce yourself to java 17
Introduce yourself to java 17
ankitbhandari32
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Curso de Java: Introdução a lambda e Streams
Curso de Java: Introdução a lambda e StreamsCurso de Java: Introdução a lambda e Streams
Curso de Java: Introdução a lambda e Streams
Helder da Rocha
 
Aula2 - SQL
Aula2 - SQLAula2 - SQL
Aula2 - SQL
Rafael Albani
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
Samuel Breed
 
Domain Driven Design com Python
Domain Driven Design com PythonDomain Driven Design com Python
Domain Driven Design com Python
Frederico Cabral
 
Upgrading To The New Map Reduce API
Upgrading To The New Map Reduce APIUpgrading To The New Map Reduce API
Upgrading To The New Map Reduce API
Tom Croucher
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Curso de OO com C# - Parte 01 - Orientação a objetos
Curso de OO com C# - Parte 01 - Orientação a objetosCurso de OO com C# - Parte 01 - Orientação a objetos
Curso de OO com C# - Parte 01 - Orientação a objetos
Leonardo Melo Santos
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
Aditya Kumar Rajan
 
Class Diagram
Class DiagramClass Diagram
Class Diagram
Seyfullah Demir
 
Diagramas De Despligue Uml
Diagramas De Despligue UmlDiagramas De Despligue Uml
Diagramas De Despligue Uml
arcangelsombra
 
Clean code: SOLID (iOS)
Clean code: SOLID (iOS)Clean code: SOLID (iOS)
Clean code: SOLID (iOS)
Maksym Husar
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
José Paumard
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScriptLotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Bill Buchan
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
Nicole Ryan
 
Herramientas CASE
Herramientas CASEHerramientas CASE
Herramientas CASE
I R
 
Introduce yourself to java 17
Introduce yourself to java 17Introduce yourself to java 17
Introduce yourself to java 17
ankitbhandari32
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Curso de Java: Introdução a lambda e Streams
Curso de Java: Introdução a lambda e StreamsCurso de Java: Introdução a lambda e Streams
Curso de Java: Introdução a lambda e Streams
Helder da Rocha
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
Samuel Breed
 
Domain Driven Design com Python
Domain Driven Design com PythonDomain Driven Design com Python
Domain Driven Design com Python
Frederico Cabral
 
Upgrading To The New Map Reduce API
Upgrading To The New Map Reduce APIUpgrading To The New Map Reduce API
Upgrading To The New Map Reduce API
Tom Croucher
 
Curso de OO com C# - Parte 01 - Orientação a objetos
Curso de OO com C# - Parte 01 - Orientação a objetosCurso de OO com C# - Parte 01 - Orientação a objetos
Curso de OO com C# - Parte 01 - Orientação a objetos
Leonardo Melo Santos
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
Aditya Kumar Rajan
 

Viewers also liked (8)

Entity Framework - Object Services
Entity Framework -  Object ServicesEntity Framework -  Object Services
Entity Framework - Object Services
Eyal Vardi
 
MVC
MVCMVC
MVC
akshin
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
Lushanthan Sivaneasharajah
 
Learn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database FirstLearn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
Introducing Entity Framework 4.0
Introducing Entity Framework 4.0Introducing Entity Framework 4.0
Introducing Entity Framework 4.0
Bishoy Demian
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design Patterns
Hatim Hakeel
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity Framework
Md. Mahedee Hasan
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
Entity Framework - Object Services
Entity Framework -  Object ServicesEntity Framework -  Object Services
Entity Framework - Object Services
Eyal Vardi
 
Learn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database FirstLearn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
Introducing Entity Framework 4.0
Introducing Entity Framework 4.0Introducing Entity Framework 4.0
Introducing Entity Framework 4.0
Bishoy Demian
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design Patterns
Hatim Hakeel
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity Framework
Md. Mahedee Hasan
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
Ad

Similar to Entity Framework Database and Code First (20)

MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
Akhil Mittal
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
James Johnson
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Entity Framework Today (May 2012)
Entity Framework Today (May 2012)
Julie Lerman
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4
James Johnson
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
glubox
 
Applying EF Code First at Your Job
Applying EF Code First at Your JobApplying EF Code First at Your Job
Applying EF Code First at Your Job
Enea Gabriel
 
Getting started with the entity framework 4.1 using asp.net mvc
Getting started with the entity framework 4.1 using asp.net mvcGetting started with the entity framework 4.1 using asp.net mvc
Getting started with the entity framework 4.1 using asp.net mvc
Steve Xu
 
Entity Framework V1 and V2
Entity Framework V1 and V2Entity Framework V1 and V2
Entity Framework V1 and V2
ukdpe
 
Just entity framework
Just entity frameworkJust entity framework
Just entity framework
Marcin Dembowski
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
nspyre_net
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
Eric Nelson
 
Entity framework
Entity frameworkEntity framework
Entity framework
Mehdi jannati
 
Programming Entity Framework Building Data Centric Apps with the ADO NET Enti...
Programming Entity Framework Building Data Centric Apps with the ADO NET Enti...Programming Entity Framework Building Data Centric Apps with the ADO NET Enti...
Programming Entity Framework Building Data Centric Apps with the ADO NET Enti...
waradegha
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5
Ehtsham Khan
 
An Overview of Entity Framework
An Overview of Entity FrameworkAn Overview of Entity Framework
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
Akhil Mittal
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
James Johnson
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Entity Framework Today (May 2012)
Entity Framework Today (May 2012)
Julie Lerman
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4
James Johnson
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
glubox
 
Applying EF Code First at Your Job
Applying EF Code First at Your JobApplying EF Code First at Your Job
Applying EF Code First at Your Job
Enea Gabriel
 
Getting started with the entity framework 4.1 using asp.net mvc
Getting started with the entity framework 4.1 using asp.net mvcGetting started with the entity framework 4.1 using asp.net mvc
Getting started with the entity framework 4.1 using asp.net mvc
Steve Xu
 
Entity Framework V1 and V2
Entity Framework V1 and V2Entity Framework V1 and V2
Entity Framework V1 and V2
ukdpe
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
nspyre_net
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
Eric Nelson
 
Programming Entity Framework Building Data Centric Apps with the ADO NET Enti...
Programming Entity Framework Building Data Centric Apps with the ADO NET Enti...Programming Entity Framework Building Data Centric Apps with the ADO NET Enti...
Programming Entity Framework Building Data Centric Apps with the ADO NET Enti...
waradegha
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5
Ehtsham Khan
 
Ad

More from James Johnson (6)

A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NET
James Johnson
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
James Johnson
 
La sql
La sqlLa sql
La sql
James Johnson
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
James Johnson
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
James Johnson
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
James Johnson
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NET
James Johnson
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
James Johnson
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
James Johnson
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
James Johnson
 

Recently uploaded (20)

Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 

Entity Framework Database and Code First

  • 2. Founder and President of the Inland Empire .NET User’s Group  Three time and current Microsoft MVP – CAD  Software developer by day  Serial netrepreneur by night
  • 4. Entity Framework  Database First  Code First  MVC Scaffolding
  • 5. Version 4 released with .NET 4.0  New version (4.3) allows for model-first, code-first or database-first development  Maps POCO objects to database objects  A collection of things instead of a dataset of rows  “things” are the entities
  • 6. Why? ◦ Adds a layer of abstraction between database and code ◦ DBA can structure database how they want ◦ Developer can map to the database how they want ◦ Rename entities for more comfortable use ◦ Entity Framework handles the mappings
  • 7. Entity Data Model – EDM ◦ Deals with the entities and relationships they use  Entities ◦ Instance of EntityType  Specification for a data type which includes a key and named set of properties ◦ Represent individual instances of the objects ◦ Customer, book, shoe, usergroup ◦ Fully typed  Relationships between look up tables are mapped as associations in the EDMX
  • 8. csdl ◦ Conceptual Schema Definition Language ◦ The conceputal schema for the EDM ◦ EntityContainer, EntitySet, EntityType definitions  ssdl ◦ Store Schema Definition Language ◦ Schematic representation of the data store  msl ◦ Mapping Specification Language ◦ Sits between the csdl and ssdl and maps the entity properties
  • 9. Lazy Loading A design pattern to defer initialization until needed context.ContextOptions.DeferredLoadingEnabled=true; List<Member> members = context.Members.ToList(); foreach(var member in members) { var memberBooks = member.Books; }
  • 10. Eager Loading Use if you will be needing every related entity List<Member> Members = context.Members.Include(“Books”).ToList(); foreach(var member in members) { var memberBooks = member.Books; }
  • 11. Contexts  The context is the instance of the entity  Passing an entity around to tiers breaks the context  Just like the song, make sure the context remains the same
  • 12. Contexts public class ModelHelper { private static Entities _db; public static Entities Entities { get { if(_db == null) _db = new Entities(); return _db; } set { _db = value; } } } private readonly Entities _db = new Entities();
  • 13. Contexts private Member AddMember(Member member, UserGroup group) { member.UserGroups.Add(group); _db.SaveChanges(); } Doesn’t work because group is in a different context private Member AddMember(Member member, UserGroup group) { var newMember = GetMember(member.Id); var newGroup = GetUserGroup(group.Id); newMember.UserGroups.Add(newGroup); _db.SaveChanges(); }
  • 14. LINQ to Entities Very similar to LINQ to SQL Selecting Member member = _db.Members.Single(x=>x.Id == id); Deleting public void DeleteMember(Member member) { _db.DeleteObject(member); _db.SaveChanges(); }
  • 15. LINQ to Entities Adding (Inserting) public void AddMember(Member member) { _db.AddToMembers(member) //this will be a list _db.SaveChanges() // of AddTo<Entities> } Editing (Updating) public void EditMember(Member member) { _db.Members.Attach(new Member{Id=member.Id}); _db.Members.ApplyCurrentValues(member); _db.SaveChanges(); }
  • 16. Repositories  Repository pattern encapsulates code into a separate class  Allows for easy changes  Can use it to switch database providers or new technologies  Stephen Walther – ASP.NET MVC Framework, Sams ◦ stephenwalther.com ◦ “Download the code” link  Add the two projects to your solution  Add references to your project
  • 17. Repositories using GenericRepository public class MyController { private readonly IGenericRepository _repo; private readonly Entities _db; public MyController() { _repo = new EFGenericRepository.EFGenericRepository(_db); } }
  • 18. Repositories _repo.Get<Member>(id); // get _repo.Edit(member); // edit _repo.Create(member); // create _repo.Delete(member); // delete // list var list = _repo.List<Member>().Where(x => x.Name.Contains(myName));
  • 19. Database First  Create the database first  Build tables and relationships  Create Entity Data Model (EDMX) in Visual Studio  Look up tables are converted to Associations
  • 21. Database First Members_Books UserGroups_Members Associations representing look up tables
  • 22. Demo
  • 23. Code First – The “Magic Unicorn”  Write code without having to define mappings in XML  Define objects in POCO  No base classes required  Enables database persistence with no configuration  Can use Data Annotations ◦ Key ◦ StringLength ◦ Required ◦ RelatedTo ◦ Etc.  DbContext ◦ Primary object to interact with a database using specific model  DbSet<TEntity> ◦ Used to perform CRUD against a specific type from the model
  • 24. Code First  Create classes  Create Context  Create Controller  Write code for ◦ Select ◦ Add ◦ Update ◦ Delete  Create Views
  • 25. Databases  By default, creates SQL Express DB ◦ <Project>.Models.<Project>Context.mdf  Can switch to SQL Compact 1. NuGet 2. Search for SqlServerCompact 3. Install Adds System.Data.SqlServerCe to references
  • 26. Databases  Add connection string settings to web.config  Name needs to match context <add name=“UserGroups” connectionString=“Data Source=|DataDirectory|UserGroups.sdf” providerName=“System.Data.SqlServerCe.4.0” />
  • 27. Databases  Run the project  UserGroups.sdf will be created
  • 28. Databases – Keeping Current  Modifying the database  Add setting to Global.asax  Implementation of IDatabaseInitializer  Deletes and recreates the database
  • 29. Databases – Keeping Current  EF 4.3.1 uses Code First Migrations ◦ Enabled by default ◦ Adds table __MigrationHistory to database  Only modifies database if model has changed
  • 30. Demo
  • 31. Scaffolding  Create MVC project  Use NuGet to update EntityFramework  Package Manager Console “Install-Package MvcScaffolding”
  • 32. Scaffolding  Add Class(es)  Build Project
  • 33. Scaffolding  Package Manager Console  “Scaffold Controller <ClassName>
  • 34. Scaffolding  Controller and Views are created
  • 35. Scaffolding – Other Commands  -ControllerName ◦ UserGroupsController – look for class “UserGroup” ◦ UserGroup – creates UserGroupsController  -ModelType ◦ Inferred from controller name ◦ Can change name of the model if needed  -Project ◦ Specify the name of the project in multi-project solutions  -CodeLanguage ◦ Specify “cs” or “vb”  -DbContextType ◦ Specify the name of the context
  • 36. Scaffolding – Other Commands  -Repository ◦ Switch. Will generate a repository class for data access  -Area ◦ For putting the generated files in a specific MVC Area  -Layout ◦ Which layout page to use if not default _Layout.cshtml  -Force ◦ Forces overwriting of existing files  -NoChildItems ◦ Will only generate the controller, no views, repositories or data contexts
  • 37. Scaffolding  Add connection string settings to web.config  Name needs to match context <add name=“UserGroupsScaffoldingContext” connectionString=“Data Source=|DataDirectory|UserGroups.sdf” providerName=“System.Data.SqlServerCe.4.0” />
  • 38. Scaffolding  Run the project  Navigate to /UserGroups/  Database is created
  • 39. Scaffolding  Scaffold the rest of the classes  “Scaffold Controller <ClassName>  Run the project  Database will be modified with new tables
  • 41. Scaffolding Relationships  It’s not you, it’s me.  Add relationships to your classes Using virtual allows EF to use Lazy Loading
  • 42. Scaffolding Relationships  Run the project again  Database is modified Look up tables are created
  • 44. Slides are at ◦ http://slidesha.re/EFScaffolding  Inland Empire .NET User’s Group ◦ 2nd Tuesday of each month ◦ www.iedotnetug.org  [email protected]  @latringo