Презентация

EntityFramework Code-First - Databases Advanced - Entity Framework - октомври 2016

 

Материали от темата

Съдържание на документа

Entity Framework:
Code First

SoftUni Team

Technical Trainers

Software University

http://softuni.bg

Database

Applications


Table of Contents

EF Modelling Workflows

Code First Main Parts

Domain Classes (Models)

DbContext and DbSet

Database connection

Using Code First Migrations

Configuring Mappings

2


3



sli.do
#Entity

Questions


EF supports two modeling workflows with code first.

4

Code first from database

Empty code first model


Why Use Code First?

Write code without having to define mappings in XML or create database models

Define objects in C# format

Reuse these models and their attributes

Enables database persistence with no configuration

Can use automatic migrations

Can use data annotations (Key, Required, etc.)



5


Main Parts

Domain Classes, DbContext and DbSet


Creating Domain Classes (Models)


Domain Classes (Models)

Bunch of normal C# classes (POCO)

May contain navigation properties











Recommended to be in a separate class library

public class PostAnswer

{

    public int PostAnswerId { get; set; }

    public string Content { get; set; }

    public int PostId { get; set; }

    public virtual Post Post { get; set; }

}

Primary key

Foreign key

Navigation property

Virtual for lazy loading

8


9

Another example of domain class (model)

Domain Classes (Models) (2)

public class Post

{

    private ICollection<PostAnswer> answers;

    public Post()

    {

        this.answers = new HashSet<PostAnswer>();

    }



    public virtual ICollection<PostAnswer> Answers

    {

        get { return this.answers; }

        set { this.answers = value; }

    }

    public PostType Type { get; set; }

}

Prevents 

NullReferenceException

Navigation property

Enumeration


10

Creating DbContext


11

A class that inherits from DbContext

Manages model classes using DbSet<T> type

Implements identity tracking, change tracking

Provides API for CRUD operations and LINQ-based data access

Recommended to be in a separate class library

Don't forget to reference the Entity Framework library 

Use the NuGet package manager

Use several DbContext if you have too much models

The DbContext Class


DbSet Type

Collection of single entity type

Set operations: Add, Attach, Remove, Find

Use with DbContext to query database

public DbSet<Post> Posts { get; set; }

12


13

Defining DbContext Class – Example

using System.Data.Entity;



using CodeFirst.Models;



public class ForumContext : DbContext

{

    public DbSet<Category> Categories { get; set; }

    public DbSet<Post> Posts { get; set; }

    public DbSet<PostAnswer> PostAnswers { get; set; }

    public DbSet<Tag> Tags { get; set; }

}


CRUD Operations with EF Code First


CRUD Operations with EF Code First

var db = new ForumContext();

var category = new Category { Name = "Database course" };

db.Categories.Add(category);

var post = new Post();

post.Title = "Homework Deadline";

post.Content = "Please extend the homework deadline";

post.Type = PostType.Normal;

post.Category = category;

post.Tags.Add(new Tag { Text = "homework" });

post.Tags.Add(new Tag { Text = "deadline" });

db.Posts.Add(post);

db.SaveChanges();

15


16

Default App.config file contains link to default connection factory











Server name by default: 

(localdb)\v11.0 or (localdb)\MSSQLLocalDB

We can use VS server explorer to view database

Where is My Data?

<entityFramework>

  <defaultConnectionFactory type="System.Data.Entity.
Infrastructure.LocalDbConnectionFactory, EntityFramework">

    <parameters>

      <parameter value="v11.0" />

    </parameters>

  </defaultConnectionFactory>

</entityFramework>


17

First, create a context constructor that calls the base constructor with connection name







Then add the connection string in app.config 

How to Connect to SQL Server?

public class ForumContext : DbContext

{

    public ForumContext() : base("ForumDb") { … }

    …

}

<connectionStrings>

  <add name="ForumDb" connectionString="Data Source=.;

    initial catalog=ForumDb;Integrated Security=True"

    providerName="System.Data.SqlClient" />

</connectionStrings>


Database Connection Workflow

Connection String Available?

Build String
(SQL Server Express or Create Local DB)

Database Exists?

Create Database

Use Database

No

Yes

No

Yes

18


19

Connecting to LocalDB:

http://stackoverflow.com/a/21565688  

Connecting to LocalDB in Visual Studio


Change Database Connection


Using Code EF First Migrations


22

What happens when we change our models?

Entity Framework compares our model with the model from the __MigrationHistory table in the DB







By default Entity Framework only creates the database

EF doesn't do any schema changes after that

Using Code First Migrations we can handle differences between models and database

Changes in Domain Classes


23

Enable Code First Migrations

Open Package Manager Console

Run Enable-Migrations command

This will create some initial jumpstart code

-EnableAutomaticMigrations for auto migrations

Two types of migrations

Automatic migrations

Set AutomaticMigrationsEnabled = true;

Code-based (providing full control)

Separate C# code file for every migration

Code First Migrations


24

CreateDatabaseIfNotExists 

Default migration

DropCreateDatabaseIfModelChanges

We lose all the data when the model changes

DropCreateDatabaseAlways

Great for automated integration testing

MigrateDatabaseToLatestVersion

This option uses our migrations

Custom migrations

Implement IDatabaseInitializer for custom migration strategy

Database Migration Strategies


25

First, enable code first migrations

Second, we need to tell to Entity Framework to use our migrations with code (or in App.config)



We can configure automatic migration

Use Code First Migrations

Database.SetInitializer(
  new MigrateDatabaseToLatestVersion<ForumContext, Configuration>());

public Configuration()

{

    this.AutomaticMigrationsEnabled = true;

    this.AutomaticMigrationDataLossAllowed = true;

}

This will allow us to delete or change properties


26

During a migration we can seed the database with some data using the Seed() method











This method will be run after each migration

Seeding the Database

protected override void Seed(ForumContext context)

{

  /* This method will be called after migrating to the latest version.   

     You can use the DbSet<T>.AddOrUpdate() helper extension method 

     to avoid creating duplicate seed data. E.g. */



  context.Tags.AddOrUpdate(t => t.Text, new Tag { Text = "C#" });

  context.SaveChanges();

}


Configure Mappings

Using Data Annotations and EF Fluent API


28

Entity Framework respects mapping details from two sources:

Data annotation attributes in the models

E.g. [Key], [Required], [MaxLength]

Can be reused for validation purposes

Fluent API code mapping configuration

By overriding OnModelCreating method

By using custom configuration classes

Use one approach or the other

Configure Mappings


29

There is a bunch of data annotation attributes

System.ComponentModel.DataAnnotations

Specify the primary key of the table: [Key]

For validation: 

[StringLength], [MaxLength], [MinLength], [Required], [Range]

Schema: 

[Column], [Table], [ComplexType], [Timestamp],  [NotMapped], [Index]

EF 6 supports custom attributes by using custom conventions

Data Annotations


Entity Framework Fluent API

Using the ModelBuilder

30


EF Fluent API for Mappings

By overriding DbContext.OnModelCreating we can specify mapping configurations:

protected override void OnModelCreating(DbModelBuilder modelBuilder)

{

  modelBuilder.Entity<Tag>()

    .HasKey(x => x.TagId);

  modelBuilder.Entity<Tag>()

    .Property(x => Text).IsUnicode(true);

  modelBuilder.Entity<Tag>()

    .Property(x => x.Text).HasMaxLength(255);

  modelBuilder.Entity<Tag>()

    .Property(x => x.Text).IsFixedLength();

  base.OnModelCreating(modelBuilder);

}

31


EF Fluent API Configurations

.Entity()

Map: Table Name, Schema

Inheritance Hierarchies, Complex Types

Entity -> Multiple Tables

Table -> Multiple Entities

Specify Key (including Composite Keys)

.Property()

Attributes (and Validation)

Map: Column Name, Type, Order

Relationships

Concurrency

32


https://softuni.bg/courses/


License

This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license

34

Attribution: this work may contain portions from

"Databases" course by Telerik Academy under CC-BY-NC-SA license


Free Trainings @ Software University

Software University Foundation – softuni.org

Software University – High-Quality Education, Profession and Job for Software Developers

softuni.bg 

	Software University @ Facebook

	facebook.com/SoftwareUniversity

	Software University @ YouTube

	youtube.com/SoftwareUniversity

	Software University Forums – forum.softuni.bg