+ All Categories

La sql

Date post: 17-Dec-2014
Category:
Upload: james-johnson
View: 296 times
Download: 3 times
Share this document with a friend
Description:
 
Popular Tags:
44
Entity Framework Database and Code First James Johnson, MVP
Transcript
Page 1: La sql

Entity FrameworkDatabase and Code

FirstJames Johnson, MVP

Page 2: La sql

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

Who I am

Page 3: La sql
Page 4: La sql

Agenda Entity Framework Database First Code First MVC Scaffolding

Page 5: La sql

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

Entity Framework

Page 6: La sql

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 Framework

Page 7: La sql

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

Entity Framework

Page 8: La sql

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

Entity Framework

Page 9: La sql

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;

}

Entity FrameworkLazy Loading

Page 10: La sql

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;

}

Entity FrameworkEager Loading

Page 11: La sql

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

Entity FrameworkContexts

Page 12: La sql

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();

Entity FrameworkContexts

Page 13: La sql

private Member AddMember(Member member, UserGroup group){ member.UserGroups.Add(group); _db.SaveChanges();}

Entity FrameworkContexts

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();}

Page 14: La sql

Very similar to LINQ to SQL

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

Deletingpublic void DeleteMember(Member member){_db.DeleteObject(member);_db.SaveChanges();

}

Entity FrameworkLINQ to Entities

Page 15: La sql

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();}

Entity FrameworkLINQ to Entities

Page 16: La sql

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

Entity FrameworkRepositories

Page 17: La sql

using GenericRepositorypublic class MyController{ private readonly IGenericRepository _repo; private readonly Entities _db;

public MyController() { _repo = new EFGenericRepository.EFGenericRepository(_db);

}}

Entity FrameworkRepositories

Page 18: La sql

_repo.Get<Member>(id); // get

_repo.Edit(member); // edit

_repo.Create(member); // create

_repo.Delete(member); // delete

// listvar list = _repo.List<Member>().Where(x =>

x.Name.Contains(myName));

Entity FrameworkRepositories

Page 19: La sql

Create the database first Build tables and relationships Create Entity Data Model (EDMX) in Visual Studio Look up tables are converted to Associations

Entity FrameworkDatabase First

Page 20: La sql

Entity FrameworkDatabase First

Page 21: La sql

Entity FrameworkDatabase First

Associations representing look up tables

Members_Books UserGroups_Members

Page 22: La sql

Entity FrameworkDemo

Page 23: La sql

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

Entity FrameworkCode First – The “Magic Unicorn”

Page 24: La sql

Create classes Create Context Create Controller Write code for

◦ Select◦ Add◦ Update◦ Delete

Create Views

Entity FrameworkCode First

Page 25: La sql

By default, creates SQL Express DB◦ <Project>.Models.<Project>Context.mdf

Can switch to SQL Compact

1. NuGet2. Search for SqlServerCompact3. Install

Adds System.Data.SqlServerCe to references

Entity FrameworkDatabases

Page 26: La sql

Add connection string settings to web.config Name needs to match context

Entity FrameworkDatabases

<add name=“UserGroups”connectionString=“Data Source=|DataDirectory|UserGroups.sdf”providerName=“System.Data.SqlServerCe.4.0” />

Page 27: La sql

Run the project UserGroups.sdf will be created

Entity FrameworkDatabases

Page 28: La sql

Modifying the database Add setting to Global.asax

Entity FrameworkDatabases – Keeping Current

Implementation of IDatabaseInitializer Deletes and recreates the database

Page 29: La sql

EF 4.3.1 uses Code First Migrations◦ Enabled by default◦ Adds table __MigrationHistory to database

Only modifies database if model has changed

Entity FrameworkDatabases – Keeping Current

Page 30: La sql

Entity FrameworkDemo

Page 31: La sql

Create MVC project Use NuGet to update EntityFramework Package Manager Console “Install-Package MvcScaffolding”

Entity FrameworkScaffolding

Page 32: La sql

Add Class(es) Build Project

Entity FrameworkScaffolding

Page 33: La sql

Package Manager Console “Scaffold Controller <ClassName>

Entity FrameworkScaffolding

Page 34: La sql

Controller and Views are created

Entity FrameworkScaffolding

Page 35: La sql

-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

Entity FrameworkScaffolding – Other Commands

Page 36: La sql

-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

Entity FrameworkScaffolding – Other Commands

Page 37: La sql

Add connection string settings to web.config Name needs to match context

Entity FrameworkScaffolding

<add name=“UserGroupsScaffoldingContext”connectionString=“Data Source=|DataDirectory|UserGroups.sdf”providerName=“System.Data.SqlServerCe.4.0” />

Page 38: La sql

Run the project Navigate to /UserGroups/ Database is created

Entity FrameworkScaffolding

Page 39: La sql

Scaffold the rest of the classes “Scaffold Controller <ClassName>

Entity FrameworkScaffolding

Run the project Database will be modified with new tables

Page 40: La sql

Entity FrameworkScaffolding

Page 41: La sql

Entity FrameworkScaffolding Relationships

It’s not you, it’s me. Add relationships to your classes

Using virtual allows EF to use Lazy Loading

Page 42: La sql

Entity FrameworkScaffolding Relationships

Run the project again Database is modified

Look up tables are created

Page 43: La sql

Questions

Page 44: La sql

Thank you

Slides are at◦http://slidesha.re/EFScaffolding

Inland Empire .NET User’s Group◦2nd Tuesday of each month◦www.iedotnetug.org

[email protected] @latringo


Recommended