25
Entity Framework (EF) Eng. Mahmoud Ouf Lecture 2 mmouf@2017

Intake 37 ef2

Embed Size (px)

Citation preview

Entity Framework(EF)

Eng. Mahmoud Ouf

Lecture 2

mmouf@2017

Role of EntitiesEntities are a conceptual model of a physical database that maps to yourbusiness domain.

This model is termed an entity data model (EDM).

The EDM is a client-side set of classes that are mapped to a physicaldatabase by Entity Framework convention and configuration.

The entities did not map directly to the database schema in so far asnaming conventions go.

You are free to restructure your entity classes to fit your needs, and theEF runtime will map your unique names to the correct database schema.

mmouf@2017

The Role of the DbContext ClassThe DbContext class represents a combination of the Unit of Work andRepository patterns that can be used to query from a database and grouptogether 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 thiscontext 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 inyour 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 PropertiesAs the name suggests, navigation properties allow you to capture JOINoperations in the Entity Framework programming model

To account for these foreign key relationships, each class in your modelcontains virtual properties that connect your classes together

Ex: public virtual ICollection<Order> Orders { get; set; }

mmouf@2017

Lazy, Eager, and Explicit LoadingThere are three ways that EF loads data into models. Lazy and Eagerfetching are based on settings on the context, and the third, Explicit, isdeveloper controlled.

Lazy Loading

The virtual modified allows EF to lazy load the data. This means that EFloads the bare minimum for each object and then retrieves additionaldetails when properties are asked for in code.

Eager Loading

Sometimes you want to load all related records.

mmouf@2017

Lazy, Eager, and Explicit LoadingExplicit Loading

Explicit loading loads a collection or class that is referenced by anavigation 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 DatabaseGenerating the Model

1. Create the solution for new application

2. (R.C.)Project=> Add New Item =>Select ADO.NET Entity DataModel

3. Then choose Add. This will launch the “ADO.NET Entity DataModel” 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 Databasenew 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 firststep of the wizard).

By default, the names of your entities will be based on the originaldatabase object names; however, the names of entities in yourconceptual 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 yourmodel.

mmouf@2017

Code First from Existing DatabaseData annotations:

Data annotations are series of attributes decorating the class and properties inthe class

They instruct EF how to build your tables and properties when generating thedatabase.

They also instruct EF how to map the data from the database to your modelclasses.

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 generatingthe DDL for the field. This attribute is also used in validations,

mmouf@2017

Code First from Existing DatabaseChanging the default mapping

The [Table("Inventory")] attribute specifies that the class maps to theInventory table. With this attribute in place, we can change the name ofthe 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 DatabaseInsert 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 DatabaseSelecting 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 DatabaseQuery 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 DatabaseDeleting 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 DatabaseUpdating 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 ModelCreate 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 ModelAdd 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 ModelInventory.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 ModelInventory.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 ModelAdd 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 ModelCustomer.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 ModelOrder.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 ModelAdding 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="datasource=.\SQLEXPRESS2014;initial catalog=AutoLot2;integratedsecurity=True;MultipleActiveResultSets=True;App=EntityFramework"providerName="System.Data.SqlClient" />

mmouf@2017

Empty Code First ModelThe DbContext file

The constructor for your derived DbContext class passes the name of theconnection 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