SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Entity Framework
(EF)
Eng. Mahmoud Ouf
Lecture 2
mmouf@2017
Role of Entities
Entities are a conceptual model of a physical database that maps to your
business domain.
This model is termed an entity data model (EDM).
The EDM is a client-side set of classes that are mapped to a physical
database by Entity Framework convention and configuration.
The entities did not map directly to the database schema in so far as
naming conventions go.
You are free to restructure your entity classes to fit your needs, and the
EF runtime will map your unique names to the correct database schema.
mmouf@2017
The Role of the DbContext Class
The DbContext class represents a combination of the Unit of Work and
Repository patterns that can be used to query from a database and group
together changes that will be written back as a single unit of work.
DbContext provides a number of core services to child classes,
including
 The ability to save all changes (which results in a database update),
 Tweak the connection string, delete objects, call stored procedures,
 Handle other fundamental details
Create a class that derives from DbContext for your specific domain.
In the constructor, pass the name of the connection string for this
context class to the base class
mmouf@2017
The Role of DbSet<T>
To add tables into your context, you add a DbSet<T> for each table in
your object model.
To enable lazy loading, the properties in the context need to be virtual.
Ex: public virtual DbSet<Customer> Customers { get; set; }
Each DbSet<T> provides a number of core services to each collection,
such as creating, deleting, and finding records in the represented table.
mmouf@2017
The Role Navigation Properties
As the name suggests, navigation properties allow you to capture JOIN
operations in the Entity Framework programming model
To account for these foreign key relationships, each class in your model
contains virtual properties that connect your classes together
Ex: public virtual ICollection<Order> Orders { get; set; }
mmouf@2017
Lazy, Eager, and Explicit Loading
There are three ways that EF loads data into models. Lazy and Eager
fetching are based on settings on the context, and the third, Explicit, is
developer controlled.
Lazy Loading
The virtual modified allows EF to lazy load the data. This means that EF
loads the bare minimum for each object and then retrieves additional
details when properties are asked for in code.
Eager Loading
Sometimes you want to load all related records.
mmouf@2017
Lazy, Eager, and Explicit Loading
Explicit Loading
Explicit loading loads a collection or class that is referenced by a
navigation property.
By default, it is set to Lazy Loading and we can re-enable it by:
context.Configuration.LazyLoadingEnabled = true;
To use Eager loading, set the LazyLoadingEnabled = false;
To use Explicit loading, use the Load method
mmouf@2017
Code First from Existing Database
Generating the Model
1. Create the solution for new application
2. (R.C.)Project=> Add New Item =>Select ADO.NET Entity Data
Model
3. Then choose Add. This will launch the “ADO.NET Entity Data
Model” Wizard
4. The wizard has 4 template:
1. EF Designer from Database
2. Empty EF Designer Model
3. Empty Code First Model
4. Code First from Database
5. Choose “Code First From Database”
mmouf@2017
Code First from Existing Database
new classes in your project:
one for each table that you selected in the wizard
one named ……Entities (the same name that you entered in the first
step of the wizard).
By default, the names of your entities will be based on the original
database object names; however, the names of entities in your
conceptual model can be anything you choose.
You can change the entity name, as well as property names of the entity,
by using special .NET attributes referred to as data annotations.
You will use data annotations to make some modifications to your
model.
mmouf@2017
Code First from Existing Database
Data annotations:
Data annotations are series of attributes decorating the class and properties in
the class
They instruct EF how to build your tables and properties when generating the
database.
They also instruct EF how to map the data from the database to your model
classes.
At the class level, the Table attribute specifies what table the class maps to.
At the property level, there are two attributes in use.
The Key attribute, this specifies the primary key for the table.
The StringLength attribute, which specifies the string length when generating
the DDL for the field. This attribute is also used in validations,
mmouf@2017
Code First from Existing Database
Changing the default mapping
The [Table("Inventory")] attribute specifies that the class maps to the
Inventory table. With this attribute in place, we can change the name of
the class to anything we want.
Change the class name (and the constructor) to Car.
In addition to the Table attribute, EF also uses the Column attribute.
By adding the [Column("PetName")] attribute to the PetName property,
we can change the name of the property to CarNickName.
mmouf@2017
Code First from Existing Database
Insert a Record (example)
private static int AddNewRecord()
{
// Add record to the Inventory table of the AutoLot database.
using (var context = new AutoLotEntities())
{
// Hard-code data for a new record, for testing.
var car = new Car() { Make = "Yugo", Color = "Brown",
CarNickName="Brownie"};
context.Cars.Add(car);
context.SaveChanges();
}
return car.CarId;
}
mmouf@2017
Code First from Existing Database
Selecting Record (example)
private static void PrintAllInventory()
{
using (var context = new AutoLotEntities())
{
foreach (Car c in context.Cars)
{
Console.WriteLine(“Name: “+ c.CarNickName);
}
}
}
mmouf@2017
Code First from Existing Database
Query with LINQ (example)
private static void PrintAllInventory()
{
using (var context = new AutoLotEntities())
{
foreach (Car c in context.Cars.Where(c => c.Make == "BMW"))
{
WriteLine(c);
}
}
}
mmouf@2017
Code First from Existing Database
Deleting Record (example)
private static void RemoveRecord(int carId)
{
// Find a car to delete by primary key.
using (var context = new AutoLotEntities())
{
Car carToDelete = context.Cars.Find(carId);
if (carToDelete != null)
{
context.Cars.Remove(carToDelete);
context.SaveChanges();
}
}
}
mmouf@2017
Code First from Existing Database
Updating Record (example)
private static void UpdateRecord(int carId)
{
using (var context = new AutoLotEntities())
{
Car carToUpdate = context.Cars.Find(carId);
if (carToUpdate != null)
{
carToUpdate.Color = "Blue";
context.SaveChanges();
}
}
}
mmouf@2017
Empty Code First Model
Create the solution for new application
(R.C.)Project=> Manage NuGet Packages
From “Browse” tab, select “Entity Framework” then “Install”
Add the Model classes (class that will be mapped to a table)
mmouf@2017
Empty Code First Model
Add the Model classes
Add files named: Customer.cs, Inventory.cs, Order.cs
In the Inventory.cs, change the class to “public partial”
Add the following namespaces (for using Data Annotation):
• System.ComponentModel.DataAnnotations
• System.ComponentModel.DataAnnotations.Schema
mmouf@2017
Empty Code First Model
Inventory.cs
public partial class Inventory
{
public int CarId { get; set; }
public string Make { get; set; }
public string Color { get; set; }
public string PetName { get; set; }
}
Then add the Data Annotation
mmouf@2017
Empty Code First Model
Inventory.cs
[Table("Inventory")]
public partial class Inventory
{
[Key]
public int CarId { get; set; }
[StringLength(50)]
public string Make { get; set; }
[StringLength(50)]
public string Color { get; set; }
[StringLength(50)]
public string PetName { get; set; }
}
mmouf@2017
Empty Code First Model
Add the navigation properties
[Table("Inventory")]
public partial class Inventory
{
[Key]
public int CarId { get; set; }
[StringLength(50)]
public string Make { get; set; }
[StringLength(50)]
public string Color { get; set; }
[StringLength(50)]
public string PetName { get; set; }
public virtual ICollection<Order> Orders { get; set; } = new HashSet<Order>();
}
mmouf@2017
Empty Code First Model
Customer.cs
public partial class Customer
{
[Key]
public int CustId { get; set; }
[StringLength(50)]
public string FirstName { get; set; }
[StringLength(50)]
public string LastName { get; set; }
[NotMapped]
public string FullName => FirstName + " " + LastName;
public virtual ICollection<Order> Orders { get; set; } = new HashSet<Order>();
}
mmouf@2017
Empty Code First Model
Order.cs
public partial class Order
{
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OrderId { get; set; }
[Required]
public int CustId { get; set; }
[Required]
public int CarId { get; set; }
[ForeignKey("CustId")]
public virtual Customer Customer { get; set; }
[ForeignKey("CarId")]
public virtual Inventory Car { get; set; }
}
mmouf@2017
Empty Code First Model
Adding the DbContext
(R.C.)The Project=> Add=> New Item=> ADO.NET Entity Data Model
Select “Empty Code First Model”
Update the *.config file and EF connection string
<add name="AutoLotConnection" connectionString="data
source=.SQLEXPRESS2014;initial catalog=AutoLot2;integrated
security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
mmouf@2017
Empty Code First Model
The DbContext file
The constructor for your derived DbContext class passes the name of the
connection string to the base DbContext class.
Open the .cs:
add the connection string to the constructor
add a DbSet for each of the model classes.
• public virtual DbSet<Customer> Customers { get; set; }
• public virtual DbSet<Inventory> Inventory { get; set; }
• public virtual DbSet<Order> Orders { get; set; }
mmouf@2017

Contenu connexe

Tendances (20)

Intake 37 1
Intake 37 1Intake 37 1
Intake 37 1
 
Intake 37 2
Intake 37 2Intake 37 2
Intake 37 2
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Linq
LinqLinq
Linq
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
LINQ
LINQLINQ
LINQ
 
Differences between method overloading and method overriding
Differences between method overloading and method overridingDifferences between method overloading and method overriding
Differences between method overloading and method overriding
 
Class and object
Class and objectClass and object
Class and object
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
Language Integrated Query - LINQ
Language Integrated Query - LINQLanguage Integrated Query - LINQ
Language Integrated Query - LINQ
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
Linq
LinqLinq
Linq
 
Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1
 
C++ programing lanuage
C++ programing lanuageC++ programing lanuage
C++ programing lanuage
 

En vedette

LIGNOFUELS 2017 FINLAND
LIGNOFUELS 2017 FINLANDLIGNOFUELS 2017 FINLAND
LIGNOFUELS 2017 FINLANDIvo Fouto
 
The five children of five nights at freddy’s
The five children of five nights at freddy’sThe five children of five nights at freddy’s
The five children of five nights at freddy’samarshmallow
 
Dep ed memorandum dm-s2016_132 ncae
Dep ed memorandum   dm-s2016_132 ncaeDep ed memorandum   dm-s2016_132 ncae
Dep ed memorandum dm-s2016_132 ncaejhaymz02
 
Tawi Customer Onboarding Process
Tawi Customer Onboarding ProcessTawi Customer Onboarding Process
Tawi Customer Onboarding Processtawi123
 
BigDataChallengesandStrategiesforanEcommerceStartup
BigDataChallengesandStrategiesforanEcommerceStartupBigDataChallengesandStrategiesforanEcommerceStartup
BigDataChallengesandStrategiesforanEcommerceStartupGaurav Tiwari
 
Common Denominators in Successful Female Statecraft: The Political Legacies o...
Common Denominators in Successful Female Statecraft: The Political Legacies o...Common Denominators in Successful Female Statecraft: The Political Legacies o...
Common Denominators in Successful Female Statecraft: The Political Legacies o...gumstaff
 
Las figuras literarias
Las figuras literariasLas figuras literarias
Las figuras literariasangel carrillo
 

En vedette (14)

OduyeluCV-1
OduyeluCV-1OduyeluCV-1
OduyeluCV-1
 
LIGNOFUELS 2017 FINLAND
LIGNOFUELS 2017 FINLANDLIGNOFUELS 2017 FINLAND
LIGNOFUELS 2017 FINLAND
 
The five children of five nights at freddy’s
The five children of five nights at freddy’sThe five children of five nights at freddy’s
The five children of five nights at freddy’s
 
Movimiento de liberación zapatista (eznl)
Movimiento de liberación zapatista (eznl)Movimiento de liberación zapatista (eznl)
Movimiento de liberación zapatista (eznl)
 
FMA500_datasheet
FMA500_datasheetFMA500_datasheet
FMA500_datasheet
 
Khattab C.V-egypt
Khattab C.V-egyptKhattab C.V-egypt
Khattab C.V-egypt
 
Bebe Jewell
Bebe JewellBebe Jewell
Bebe Jewell
 
Dep ed memorandum dm-s2016_132 ncae
Dep ed memorandum   dm-s2016_132 ncaeDep ed memorandum   dm-s2016_132 ncae
Dep ed memorandum dm-s2016_132 ncae
 
Hadoop12
Hadoop12Hadoop12
Hadoop12
 
Tawi Customer Onboarding Process
Tawi Customer Onboarding ProcessTawi Customer Onboarding Process
Tawi Customer Onboarding Process
 
BigDataChallengesandStrategiesforanEcommerceStartup
BigDataChallengesandStrategiesforanEcommerceStartupBigDataChallengesandStrategiesforanEcommerceStartup
BigDataChallengesandStrategiesforanEcommerceStartup
 
Common Denominators in Successful Female Statecraft: The Political Legacies o...
Common Denominators in Successful Female Statecraft: The Political Legacies o...Common Denominators in Successful Female Statecraft: The Political Legacies o...
Common Denominators in Successful Female Statecraft: The Political Legacies o...
 
Las figuras literarias
Las figuras literariasLas figuras literarias
Las figuras literarias
 
Evq1.2
Evq1.2Evq1.2
Evq1.2
 

Similaire à Intake 37 ef2

Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Svetlin Nakov
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Tomas Petricek
 
Learning .NET Attributes
Learning .NET AttributesLearning .NET Attributes
Learning .NET AttributesPooja Gaikwad
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributessonia merchant
 
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
 
05 entity framework
05 entity framework05 entity framework
05 entity frameworkglubox
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
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
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 

Similaire à Intake 37 ef2 (20)

Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
Learning .NET Attributes
Learning .NET AttributesLearning .NET Attributes
Learning .NET Attributes
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
 
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
 
Ef code first
Ef code firstEf code first
Ef code first
 
Practical OData
Practical ODataPractical OData
Practical OData
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
La sql
La sqlLa sql
La sql
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
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
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 

Plus de Mahmoud Ouf

Plus de Mahmoud Ouf (20)

Relation between classes in arabic
Relation between classes in arabicRelation between classes in arabic
Relation between classes in arabic
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4
 
Intake 38 data access 1
Intake 38 data access 1Intake 38 data access 1
Intake 38 data access 1
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Intake 38 11
Intake 38 11Intake 38 11
Intake 38 11
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Intake 38 7
Intake 38 7Intake 38 7
Intake 38 7
 
Intake 38 6
Intake 38 6Intake 38 6
Intake 38 6
 
Intake 38 5 1
Intake 38 5 1Intake 38 5 1
Intake 38 5 1
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
Intake 37 DM
Intake 37 DMIntake 37 DM
Intake 37 DM
 
Intake 37 12
Intake 37 12Intake 37 12
Intake 37 12
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
Intake 37 10
Intake 37 10Intake 37 10
Intake 37 10
 
Intake 37 9
Intake 37 9Intake 37 9
Intake 37 9
 
Intake 37 8
Intake 37 8Intake 37 8
Intake 37 8
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 

Dernier

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 

Dernier (20)

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Intake 37 ef2

  • 1. Entity Framework (EF) Eng. Mahmoud Ouf Lecture 2 mmouf@2017
  • 2. Role of Entities Entities are a conceptual model of a physical database that maps to your business domain. This model is termed an entity data model (EDM). The EDM is a client-side set of classes that are mapped to a physical database by Entity Framework convention and configuration. The entities did not map directly to the database schema in so far as naming conventions go. You are free to restructure your entity classes to fit your needs, and the EF runtime will map your unique names to the correct database schema. mmouf@2017
  • 3. The Role of the DbContext Class The DbContext class represents a combination of the Unit of Work and Repository patterns that can be used to query from a database and group together changes that will be written back as a single unit of work. DbContext provides a number of core services to child classes, including  The ability to save all changes (which results in a database update),  Tweak the connection string, delete objects, call stored procedures,  Handle other fundamental details Create a class that derives from DbContext for your specific domain. In the constructor, pass the name of the connection string for this context class to the base class mmouf@2017
  • 4. The Role of DbSet<T> To add tables into your context, you add a DbSet<T> for each table in your object model. To enable lazy loading, the properties in the context need to be virtual. Ex: public virtual DbSet<Customer> Customers { get; set; } Each DbSet<T> provides a number of core services to each collection, such as creating, deleting, and finding records in the represented table. mmouf@2017
  • 5. The Role Navigation Properties As the name suggests, navigation properties allow you to capture JOIN operations in the Entity Framework programming model To account for these foreign key relationships, each class in your model contains virtual properties that connect your classes together Ex: public virtual ICollection<Order> Orders { get; set; } mmouf@2017
  • 6. Lazy, Eager, and Explicit Loading There are three ways that EF loads data into models. Lazy and Eager fetching are based on settings on the context, and the third, Explicit, is developer controlled. Lazy Loading The virtual modified allows EF to lazy load the data. This means that EF loads the bare minimum for each object and then retrieves additional details when properties are asked for in code. Eager Loading Sometimes you want to load all related records. mmouf@2017
  • 7. Lazy, Eager, and Explicit Loading Explicit Loading Explicit loading loads a collection or class that is referenced by a navigation property. By default, it is set to Lazy Loading and we can re-enable it by: context.Configuration.LazyLoadingEnabled = true; To use Eager loading, set the LazyLoadingEnabled = false; To use Explicit loading, use the Load method mmouf@2017
  • 8. Code First from Existing Database Generating the Model 1. Create the solution for new application 2. (R.C.)Project=> Add New Item =>Select ADO.NET Entity Data Model 3. Then choose Add. This will launch the “ADO.NET Entity Data Model” Wizard 4. The wizard has 4 template: 1. EF Designer from Database 2. Empty EF Designer Model 3. Empty Code First Model 4. Code First from Database 5. Choose “Code First From Database” mmouf@2017
  • 9. Code First from Existing Database new classes in your project: one for each table that you selected in the wizard one named ……Entities (the same name that you entered in the first step of the wizard). By default, the names of your entities will be based on the original database object names; however, the names of entities in your conceptual model can be anything you choose. You can change the entity name, as well as property names of the entity, by using special .NET attributes referred to as data annotations. You will use data annotations to make some modifications to your model. mmouf@2017
  • 10. Code First from Existing Database Data annotations: Data annotations are series of attributes decorating the class and properties in the class They instruct EF how to build your tables and properties when generating the database. They also instruct EF how to map the data from the database to your model classes. At the class level, the Table attribute specifies what table the class maps to. At the property level, there are two attributes in use. The Key attribute, this specifies the primary key for the table. The StringLength attribute, which specifies the string length when generating the DDL for the field. This attribute is also used in validations, mmouf@2017
  • 11. Code First from Existing Database Changing the default mapping The [Table("Inventory")] attribute specifies that the class maps to the Inventory table. With this attribute in place, we can change the name of the class to anything we want. Change the class name (and the constructor) to Car. In addition to the Table attribute, EF also uses the Column attribute. By adding the [Column("PetName")] attribute to the PetName property, we can change the name of the property to CarNickName. mmouf@2017
  • 12. Code First from Existing Database Insert a Record (example) private static int AddNewRecord() { // Add record to the Inventory table of the AutoLot database. using (var context = new AutoLotEntities()) { // Hard-code data for a new record, for testing. var car = new Car() { Make = "Yugo", Color = "Brown", CarNickName="Brownie"}; context.Cars.Add(car); context.SaveChanges(); } return car.CarId; } mmouf@2017
  • 13. Code First from Existing Database Selecting Record (example) private static void PrintAllInventory() { using (var context = new AutoLotEntities()) { foreach (Car c in context.Cars) { Console.WriteLine(“Name: “+ c.CarNickName); } } } mmouf@2017
  • 14. Code First from Existing Database Query with LINQ (example) private static void PrintAllInventory() { using (var context = new AutoLotEntities()) { foreach (Car c in context.Cars.Where(c => c.Make == "BMW")) { WriteLine(c); } } } mmouf@2017
  • 15. Code First from Existing Database Deleting Record (example) private static void RemoveRecord(int carId) { // Find a car to delete by primary key. using (var context = new AutoLotEntities()) { Car carToDelete = context.Cars.Find(carId); if (carToDelete != null) { context.Cars.Remove(carToDelete); context.SaveChanges(); } } } mmouf@2017
  • 16. Code First from Existing Database Updating Record (example) private static void UpdateRecord(int carId) { using (var context = new AutoLotEntities()) { Car carToUpdate = context.Cars.Find(carId); if (carToUpdate != null) { carToUpdate.Color = "Blue"; context.SaveChanges(); } } } mmouf@2017
  • 17. Empty Code First Model Create the solution for new application (R.C.)Project=> Manage NuGet Packages From “Browse” tab, select “Entity Framework” then “Install” Add the Model classes (class that will be mapped to a table) mmouf@2017
  • 18. Empty Code First Model Add the Model classes Add files named: Customer.cs, Inventory.cs, Order.cs In the Inventory.cs, change the class to “public partial” Add the following namespaces (for using Data Annotation): • System.ComponentModel.DataAnnotations • System.ComponentModel.DataAnnotations.Schema mmouf@2017
  • 19. Empty Code First Model Inventory.cs public partial class Inventory { public int CarId { get; set; } public string Make { get; set; } public string Color { get; set; } public string PetName { get; set; } } Then add the Data Annotation mmouf@2017
  • 20. Empty Code First Model Inventory.cs [Table("Inventory")] public partial class Inventory { [Key] public int CarId { get; set; } [StringLength(50)] public string Make { get; set; } [StringLength(50)] public string Color { get; set; } [StringLength(50)] public string PetName { get; set; } } mmouf@2017
  • 21. Empty Code First Model Add the navigation properties [Table("Inventory")] public partial class Inventory { [Key] public int CarId { get; set; } [StringLength(50)] public string Make { get; set; } [StringLength(50)] public string Color { get; set; } [StringLength(50)] public string PetName { get; set; } public virtual ICollection<Order> Orders { get; set; } = new HashSet<Order>(); } mmouf@2017
  • 22. Empty Code First Model Customer.cs public partial class Customer { [Key] public int CustId { get; set; } [StringLength(50)] public string FirstName { get; set; } [StringLength(50)] public string LastName { get; set; } [NotMapped] public string FullName => FirstName + " " + LastName; public virtual ICollection<Order> Orders { get; set; } = new HashSet<Order>(); } mmouf@2017
  • 23. Empty Code First Model Order.cs public partial class Order { [Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int OrderId { get; set; } [Required] public int CustId { get; set; } [Required] public int CarId { get; set; } [ForeignKey("CustId")] public virtual Customer Customer { get; set; } [ForeignKey("CarId")] public virtual Inventory Car { get; set; } } mmouf@2017
  • 24. Empty Code First Model Adding the DbContext (R.C.)The Project=> Add=> New Item=> ADO.NET Entity Data Model Select “Empty Code First Model” Update the *.config file and EF connection string <add name="AutoLotConnection" connectionString="data source=.SQLEXPRESS2014;initial catalog=AutoLot2;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /> mmouf@2017
  • 25. Empty Code First Model The DbContext file The constructor for your derived DbContext class passes the name of the connection string to the base DbContext class. Open the .cs: add the connection string to the constructor add a DbSet for each of the model classes. • public virtual DbSet<Customer> Customers { get; set; } • public virtual DbSet<Inventory> Inventory { get; set; } • public virtual DbSet<Order> Orders { get; set; } mmouf@2017