SlideShare una empresa de Scribd logo
1 de 44
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 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
   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

Más contenido relacionado

La actualidad más candente

Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialSyed Shahul
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Khaled Anaqwa
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the ContextRussell Castagnaro
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0Korhan Bircan
 
Sqlite
SqliteSqlite
SqliteKumar
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqliteArif Huda
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WPNguyen Tuan
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOSMake School
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database TutorialPerfect APK
 
Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Fwdays
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jjJoe Jacob
 

La actualidad más candente (20)

Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Android Database
Android DatabaseAndroid Database
Android Database
 
Local Storage
Local StorageLocal Storage
Local Storage
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the Context
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
REST Basics
REST BasicsREST Basics
REST Basics
 
Sqlite
SqliteSqlite
Sqlite
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqlite
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOS
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
 
Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 

Destacado

Neighborhood Interfaith Council Marketing Presentation
Neighborhood Interfaith Council Marketing PresentationNeighborhood Interfaith Council Marketing Presentation
Neighborhood Interfaith Council Marketing PresentationNicole Newman
 
Sl chattanooga beh_chng_2010
Sl chattanooga beh_chng_2010Sl chattanooga beh_chng_2010
Sl chattanooga beh_chng_2010Sharon Roerty
 
Evoluzione degli strumenti di sviluppo Microsoft
Evoluzione degli strumenti di sviluppo MicrosoftEvoluzione degli strumenti di sviluppo Microsoft
Evoluzione degli strumenti di sviluppo MicrosoftMassimo Bonanni
 
Week of sept. 6
Week of sept. 6Week of sept. 6
Week of sept. 6krehd
 
Подмосковье - Территория Футбола
Подмосковье - Территория ФутболаПодмосковье - Территория Футбола
Подмосковье - Территория ФутболаMaxim Doronin
 

Destacado (8)

Calendar Products
Calendar ProductsCalendar Products
Calendar Products
 
Neighborhood Interfaith Council Marketing Presentation
Neighborhood Interfaith Council Marketing PresentationNeighborhood Interfaith Council Marketing Presentation
Neighborhood Interfaith Council Marketing Presentation
 
Sl chattanooga beh_chng_2010
Sl chattanooga beh_chng_2010Sl chattanooga beh_chng_2010
Sl chattanooga beh_chng_2010
 
Berkeley Board Fellows Kick off Presentation 10-22-2010
Berkeley Board Fellows Kick off Presentation 10-22-2010Berkeley Board Fellows Kick off Presentation 10-22-2010
Berkeley Board Fellows Kick off Presentation 10-22-2010
 
Evoluzione degli strumenti di sviluppo Microsoft
Evoluzione degli strumenti di sviluppo MicrosoftEvoluzione degli strumenti di sviluppo Microsoft
Evoluzione degli strumenti di sviluppo Microsoft
 
Week of sept. 6
Week of sept. 6Week of sept. 6
Week of sept. 6
 
Подмосковье - Территория Футбола
Подмосковье - Территория ФутболаПодмосковье - Территория Футбола
Подмосковье - Территория Футбола
 
Semantics
SemanticsSemantics
Semantics
 

Similar a La sql

Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4James Johnson
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Svetlin Nakov
 
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
 
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 UnicornsRichie Rump
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 
Microsoft Entity Framework
Microsoft Entity FrameworkMicrosoft Entity Framework
Microsoft Entity FrameworkMahmoud Tolba
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity FrameworkJames Johnson
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2Neeraj Mathur
 
05 entity framework
05 entity framework05 entity framework
05 entity frameworkglubox
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfitallanh0526
 
Obevo Javasig.pptx
Obevo Javasig.pptxObevo Javasig.pptx
Obevo Javasig.pptxLadduAnanu
 
MongoDB Knowledge share
MongoDB Knowledge shareMongoDB Knowledge share
MongoDB Knowledge shareMr Kyaing
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedIMC Institute
 

Similar a La sql (20)

Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 
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...
 
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
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
Microsoft Entity Framework
Microsoft Entity FrameworkMicrosoft Entity Framework
Microsoft Entity Framework
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
Practical OData
Practical ODataPractical OData
Practical OData
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfit
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Obevo Javasig.pptx
Obevo Javasig.pptxObevo Javasig.pptx
Obevo Javasig.pptx
 
MongoDB Knowledge share
MongoDB Knowledge shareMongoDB Knowledge share
MongoDB Knowledge share
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 

Más de 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 .NETJames 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 .NETJames Johnson
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
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 4James Johnson
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4James Johnson
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryJames Johnson
 

Más de 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
 
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
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
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
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 

Último

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

La sql

  • 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
  • 3.
  • 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
  • 43.
  • 44. 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